Calling multiple functions from Salesforce Javascript Button - javascript

I'm fairly new at javascript, so this might be a silly question.
I've built a javascript button in Salesforce that does the following when clicked (http://i.stack.imgur.com/hqMhp.png)
What I'd like it to do for now is just display 4 separate alerts (I'll add in the real functions later).
Here's the code I'm using:
{!REQUIRESCRIPT("/soap/ajax/20.0/connection.js")}
var leadObj = new sforce.SObject("Lead");
var countryVal = "{!Lead.Country }";
var leadID = "{!Lead.Id}";
var ownerID = "{!Lead.OwnerId }";
function insertScript(script){
var targetNode = document.createElement('div'); // construct div for script injection
document.body.appendChild(targetNode);
try {
var el = document.createElement('script');
el.type="text/javascript";
el.innerHTML = script;
targetNode.appendChild(el);
} catch (e){
var el = document.createElement('span');
targetNode.appendChild(el);
el.innerHTML = "<br /><scr"+"ipt type='text/javascript' defer='defer'>"+script+"</script" + ">";
}
var box = new SimpleDialog("hersh"+Math.random(), true);
parent.box = box;
box.setTitle("Lead Rerouter");
box.createDialog();
box.setWidth(350);
box.setContentInnerHTML("<p align='center'><img src='/img/icon/profile24.png' style='margin:0 5px;'/><img src='/img/sales/quotes/sync_overlay_arrow.png' style='margin:5px;'/><img src='/img/icon/custom51_100/globe24.png' style='margin:0 5px;'/></p><p align='center'>Which region should this lead be routed to?</p><p align='center'><br /><button class='btn' onclick='routeAPAC(); return false;'>APAC</button><button class='btn' onclick='routeEMEA(); return false;'>EMEA</button><button class='btn' onclick='routeNA(); return false;'>NA</button><button class='btn' onclick='routeLATAM(); return false;'>LATAM</button><br><button class='btn' onclick='window.parent.box.hide(); return false;'>Cancel</button></p>");
box.setupDefaultButtons();
box.show();
}
script = "function routeAPAC(){alert (\"Lead routed to APAC!\")}";
script = "function routeEMEA(){alert (\"Lead routed to EMEA!\")}";
script = "function routeNA(){alert (\"Lead routed to NA!\")}";
script = "function routeLATAM(){alert (\"Lead routed to LATAM!\")}";
insertScript(script);
What am I doing wrong here?
Thanks!

You are over-complicating it.
document.querySelector(".generatorbutton").onclick = function() {
//add the window
}
var actionlist = {
".apa": function(){
//things to do onclick
},
".emea": function(){
//things to do onclick
},
".na": function(){
//things to do onclick
},
".latam": function(){
//things to do onclick
},
};
for(selector in actionlist) {
document.querySelector(selector).onclick = actionlist[selector];
}
Take a look at this for future references.
Hope this helps!

Due to overwriting of script variable, In your above code you can have only last one function routeLATAM will define through insertScript function
If you concatenate like below you will see all function definitions available
script = "function routeAPAC(){alert (\"Lead routed to APAC!\")}";
script += "function routeEMEA(){alert (\"Lead routed to EMEA!\")}";
script += "function routeNA(){alert (\"Lead routed to NA!\")}";
script += "function routeLATAM(){alert (\"Lead routed to LATAM!\")}";
insertScript(script);

Related

Print Options Do Not Open

I have an html file in google script with JS, trying to print using the following code. It opens the document without the print options, I still have to do the cmd+P to print. Any idea, please?
function printBadge() {
var attendee = document.getElementById("info").value;
var fullName = "xxx";
var snb = "xxx";
var printFonts = "fonts";
var printStyle = "style";
var printArea = "badge info";
w = window.open();
w.document.write(printFonts + printStyle + printArea).html();
w.document.close();
w.focus();
w.print();
w.close();
return false;
}
The reason is this line w.document.write(printFonts + printStyle + printArea).html();. There is no function .html() associated to document.write and when you try to execute it, it fails there and so window gets stuck.
It needs to be w.document.write(printFonts + printStyle + printArea) without .html() function.
Hope it helps. Revert for any doubts.

Cross Domain Ajax Call Not Working with document.write

I am using this Ajax script below to make cross domain Ajax calls which works fine if i use alert(txt);, but when i change it to document.write(txt); to print the result it stops working and i am not sure why it is not working,
It might be something stupid but i just can't figure it out
function xss_ajax(url) {
var script_id = null;
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
script.setAttribute('id', 'script_id');
script_id = document.getElementById('script_id');
if(script_id){
document.getElementsByTagName('head')[0].removeChild(script_id);
}
// Insert <script> into DOM
document.getElementsByTagName('head')[0].appendChild(script);
}
function callback(data) {
var txt = '';
for(var key in data) {
txt += key + " " + data[key];
}
//alert(txt);
document.write(txt);
}
var url = "http://myserver.com";
I believe that in some browsers you cannot call document.write after the document is done loading...
Edit: This stuff I'm striking out certainly does not work. As Teemu points out, calling "open" clears out the document. Also, MDN says that calling .write will implicitly call .open if you did not call it yourself. The other possibility is that the document is just not rendering because when you start writing you'll have to close the stream. You could try (not really sure if this works):
document.open();
document.write('stuff');
document.close();
However, I would strongly recommend that you just use a more standard method for writing to the document such as appendChild or using a framework (e.g. jQuery):
function callback(data) {
var txt = '';
for(var key in data) {
txt += key + " " + data[key];
}
//alert(txt);
//document.write(txt);
document.body.appendChild(document.createTextNode(txt));
}

No data in callback : how to pause load of a javascript function

We are having an issue in the following javascript code.
doCallback function is happening before doMainProcess gets finished.
So every time we get result = null in the doCallback.
Is there a way to pause load of the doCallback to wait until we get the result ?
Edit: setResult is happening multiple times and is asynchronous via iframe, and we don't know timing. Also callback only happens some of the time decided by another process.
So we can not simply change the position of doCallback.
<html>
<head>
<script>
var result;
var callback = "callback";
var url = "http://www.example2.com/getResponse/";
function iframeCallback() {
var iframe = document.createElement('iframe');
iframe.style.border='0px';
iframe.style.width ='0px';
iframe.style.height='0px';
document.body.appendChild(iframe);
var iDocument;
if (iframe.contentDocument) {
iDocument = iframe.contentDocument;
} else if (iframe.contentWindow) {
iDocument = iframe.contentWindow.document;
} else if (iframe.document) {
iDocument = iframe.document;
}
var content = "<script type='text/javascript'>";
content += "var jsText = \"<script type='text/javascript' src='" + url + "'></\" + \"script>\";";
content += "document.write(jsText);";
content += "</"+"script>";
content += "<script type='text/javascript'>";
content += "var data = eval('"+callback+"');";
content += "window.parent.setResult(data);";
content += "</"+"script>";
iDocument.open();
iDocument.write(content);
iDocument.close();
}
function setResult(data) {
result = data;
}
function doMainProcess() {
iframeCallback()
}
function doCallback() {
//we need to wait here until we get the result.
alert(result);
}
</script>
</head>
<body>
<script>
doMainProcess();
</script>
<script>
doCallback();
</script>
</body>
<html>
Yes,
delete this:
<script>
doCallback();
</script>
Change this:
function setResult(data) {
result = data;
}
to this:
function setResult(data) {
result = data;
doCallback();
}
A clunky solution (that doesn't involve my having to read your code carefully):
var readyForCallback = false;
function doMainProcess() {
// your code here
readyForCallback = true;
}
function doCallback(arg1,arg2,arg3,etc) {
if (!readyForCallback) {
// anonymous function as way to keep the original callback
// argument(s) with a timeout
setTimeout(function(){doCallback(arg1,arg2,arg3,etc);},20);
return;
}
// your code here
}
Note: within your timeout function you could also use doCallback.apply() with the arguments object to automatically handle any number of arguments, but I didn't include this in my code because off-hand I forget whether you can just use the arguments object directly or if you'd have to first create a proper array populated from arguments.

Inserting Google Adwords Conversion Tracking with Javascript or jQuery

I'm pretty new to javascript, and therein probably lies my problem. I'm trying to track AdWords conversions that occur within a widget on our site. The user fills in a form and the result from the widget is published in the same div without a page refresh. The issue I'm having is when I try to appendChild (or append in jQuery) both script elements in Google's code (shown below) the page gets 302 redirected to a blank Google page (or at least that's what it looks like through FireBug).
I'm able to provide a callback method for the results of the form, and that's where I'm trying to insert the AdWords tracking code. For reference, this is the code provided by Google:
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 993834405;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "bSpUCOP9iAIQpevy2QM";
/* ]]> */
</script>
<script type="text/javascript" src="http://www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/993834405/?label=bSpUCOP9iAIQpevy2QM&guid=ON&script=0"/>
</div>
</noscript>
Pretty standard stuff. So, what I'm trying to do is insert this into the results page using the callback method (which is provided). Frankly, I'm redirected no matter when I try to insert this code using js or jQuery (either on original page load or in the callback) so maybe the callback bit is irrelevant, but it's why I'm not just pasting it into the page's code.
I've tried a number of different ways to do this, but here's what I currently have (excuse the sloppiness. Just trying to hack my way through this at the moment!):
function matchResultsCallback(data){
var scriptTag = document.createElement('script');
scriptTag.type = "text/javascript";
scriptTag.text = scriptTag.text + "/* <![CDATA[ */\n";
scriptTag.text = scriptTag.text + "var google_conversion_id \= 993834405\;\n";
scriptTag.text = scriptTag.text + "var google_conversion_language \= \"en\"\;\n";
scriptTag.text = scriptTag.text + "var google_conversion_format \= \"3\"\;\n";
scriptTag.text = scriptTag.text + "var google_conversion_color \= \"ffffff\"\;\n";
scriptTag.text = scriptTag.text + "var google_conversion_label \= \"bSpUCOP9iAIQpevy2QM\"\;\n";
scriptTag.text = scriptTag.text + "/* ]]> */\n";
$('body').append(scriptTag);
$('body').append("<script type\=\"text\/javascript\" src\=\"http://www.googleadservices.com/pagead/conversion.js\" />");
//I have also tried this bit above using the same method as 'scriptTag' with no luck, this is just the most recent iteration.
var scriptTag2 = document.createElement('noscript');
var imgTag = document.createElement('img');
imgTag.height = 1;
imgTag.width = 1;
imgTag.border = 0;
imgTag.src = "http://www.googleadservices.com/pagead/conversion/993834405/?label=bSpUCOP9iAIQpevy2QM&guid=ON&script=0";
$('body').append(scriptTag2);
$('noscript').append(imgTag);
}
The really odd thing is that when I only insert one of the script tags (it doesn't matter which one), it doesn't redirect. It only redirects when I try to insert both of them.
I've also tried putting the first script tag into the original page code (as it's not making any calls anywhere, it's just setting variables) and just inserting the conversions.js file and it still does the redirect.
If it's relevant I'm using Firefox 3.6.13, and have tried the included code with both jQuery 1.3 and 1.5 (after realizing we were using v1.3).
I know I'm missing something! Any suggestions?
Nowadays it is convenient to use the Asynchronous Tag at http://www.googleadservices.com/pagead/conversion_async.js that exposes the window.google_trackConversion function.
This function can be used at any time. For example after submitting a form, like in your case.
See https://developers.google.com/adwords-remarketing-tag/asynchronous/
Update 2018
Situation changed and it seems that you have more options now with the gtag.js: https://developers.google.com/adwords-remarketing-tag/
If you're using jQuery in your pages, why don't you use the getScript method of the same to poll the conversion tracking script after setting the required variables?
This is what I usually do, once I've received a success response from my AJAX calls.
var google_conversion_id = <Your ID Here>;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "<Your Label here>";
var google_conversion_value = 0;
if (100) {
google_conversion_value = <Your value here if any>;
}
$jQ.getScript( "http://www.googleadservices.com/pagead/conversion.js" );
This works just fine for me. If you want a more detailed example:
$.ajax({
async: true,
type: "POST",
dataType: "json",
url: <Your URL>,
data: _data,
success: function( json ) {
// Do something
// ...
// Track conversion
var google_conversion_id = <Your ID Here>;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "<Your Label here>";
var google_conversion_value = 0;
if (100) {
google_conversion_value = <Your value here if any>;
}
$.getScript( "http://www.googleadservices.com/pagead/conversion.js" );
} // success
});
If you use other libraries such as Mootools or Prototype, I'm sure they have similar in-built methods. This AFAIK is one of the cleanest approaches.
this simple code worked for me (the $.getScript version didn't).
var image = new Image(1,1);
image.src = 'http://www.googleadservices.com/pagead/conversion/' + id + '/?label=' + label + ' &guid=ON&script=0';
// This takes care of it for jQuery. Code can be easily adapted for other javascript libraries:
function googleTrackingPixel() {
// set google variables as globals
window.google_conversion_id = 1117861175
window.google_conversion_language = "en"
window.google_conversion_format = "3"
window.google_conversion_color = "ffffff"
window.google_conversion_label = "Ll49CJnRpgUQ9-at5QM"
window.google_conversion_value = 0
var oldDocWrite = document.write // save old doc write
document.write = function(node){ // change doc write to be friendlier, temporary
$("body").append(node)
}
$.getScript("http://www.googleadservices.com/pagead/conversion.js", function() {
setTimeout(function() { // let the above script run, then replace doc.write
document.write = oldDocWrite
}, 100)
})
}
// and you would call it in your script on the event like so:
$("button").click( function() {
googleTrackingPixel()
})
In your Adwords account - if you change the conversion tracking event to "Click" instead of "Page Load" it will provide you with code that creates a function. It creates a snippet like this:
<!-- Google Code for Developer Contact Form Conversion Page
In your html page, add the snippet and call
goog_report_conversion when someone clicks on the
chosen link or button. -->
<script type="text/javascript">
/* <![CDATA[ */
goog_snippet_vars = function() {
var w = window;
w.google_conversion_id = <Your ID Here>;
w.google_conversion_label = "<Your value here if any>";
w.google_remarketing_only = false;
}
// DO NOT CHANGE THE CODE BELOW.
goog_report_conversion = function(url) {
goog_snippet_vars();
window.google_conversion_format = "3";
window.google_is_call = true;
var opt = new Object();
opt.onload_callback = function() {
if (typeof(url) != 'undefined') {
window.location = url;
}
}
var conv_handler = window['google_trackConversion'];
if (typeof(conv_handler) == 'function') {
conv_handler(opt);
}
}
/* ]]> */
</script>
<script type="text/javascript"
src="//www.googleadservices.com/pagead/conversion_async.js">
</script>
Then in your code you just call:
goog_report_conversion();
Or for a link or image click:
click here
After trying everything the link Funka provided (http://articles.adamwrobel.com/2010/12/23/trigger-adwords-conversion-on-javascript-event) was what worked for me. Like he said it's scary to overwrite document.write, but
It seems like this is what you have to do unless you can load the script before the page load.
Since the script uses document.write so it needs to be re-written
document.write = function(node){ // exactly what document.write should of been doing..
$("body").append(node);
}
window.google_tag_params = {
prodid: pageId,
pagetype: pageTypes[pageType] || "",
value: "234324342"
};
window.google_conversion_id = 2324849237;
window.google_conversion_label = "u38234j32423j432kj4";
window.google_custom_params = window.google_tag_params;
window.google_remarketing_only = true;
$.getScript("http://www.googleadservices.com/pagead/conversion.js")
.done(function() {
// script is loaded.
});
See https://gist.github.com/c7a316972128250d278c
As you have seen, the google conversion tag only calls on a redraw. I had to make sure it was called when a part of a page was redrawn. (Due to some bad website design that I could not fix at the moment.) So I wrote a function to call from an onClick event.
Essentially, all you have to do is to call doConversion();
Here is what we ended up with:
// gothelp from from http://www.ewanheming.com/2012/01/web-analytics/website-tracking/adwords-page-event-conversion-tracking
var Goal = function(id, label, value, url) {
this.id = id;
this.label = label;
this.value = value;
this.url = url;
};
function trackAdWordsConversion(goal, callback) {
// Create an image
var img = document.createElement("img");
// An optional callback function to run follow up processed after the conversion has been tracked
if(callback && typeof callback === "function") {
img.onload = callback;
}
// Construct the tracking beacon using the goal parameters
var trackingUrl = "http://www.googleadservices.com/pagead/conversion/"+goal.id;
trackingUrl += "/?random="+new Date().getMilliseconds();
trackingUrl += "&value="+goal.value;
trackingUrl += "&label="+goal.label;
trackingUrl += "&guid=ON&script=0&url="+encodeURI(goal.url);
img.src = trackingUrl;
// Add the image to the page
document.body.appendChild(img);
// Don't display the image
img.style = "display: none;";
}
function linkClick(link, goal) {
try {
// A function to redirect the user after the conversion event has been sent
var linkClickCallback = function() {
window.location = link.href;
};
// Track the conversion
trackAdWordsConversion(goal, linkClickCallback);
// Don't keep the user waiting too long in case there are problems
setTimeout(linkClickCallback, 1000);
// Stop the default link click
return false;
} catch(err) {
// Ensure the user is still redirected if there's an unexpected error in the code
return true;
}
}
function doConversion() {
var g = new Goal(YOUR CODE,YOUR_COOKIE,0.0,location.href);
return linkClick(this,g);
}
I tried all the ways to manually include conversion.js, it all loaded the script, but didn't further execute what we needed inside the script, there's a simple solution.
Just put your conversion code in a separate HTML, and load it in an iframe.
I found code to do that at http://www.benjaminkim.com/ that seemed to work well.
function ppcconversion() {
var iframe = document.createElement('iframe');
iframe.style.width = '0px';
iframe.style.height = '0px';
document.body.appendChild(iframe);
iframe.src = '/track.html'; // put URL to tracking code here.
};
then just call ppcconversion() wherever in the JS you like to record it.
All I do is return the code (or in our case, an image) along with the "success" message in the callback.
When a contact form is submitted, or a registration form filled out and submitted, we post to a php script using jQuery, then output a "thank-you" message to a div:
"$first_name, Thanks for requesting more information. A representative will contact you shortly."
... followed by the 1x1 gif Google provides.
Here's the jQuery:
$.post('script.php',{'first_name':first_name,'last_name':last_name,'email':email,'phone1':phone1,'password':password,},function(data){
var result=data.split("|");
if(result[0] ==='success'){
$('#return').html(result[1] + $result[2]);
And the php...
echo 'success|'.$first_name.', Thanks for requesting more information.
A representative will contact you shortly.|<img height="1" width="1" alt="" src="http://www.googleadservices.com/pagead/conversion/xxxxxxxx/imp.gif?value=0&label=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&script=0"/>';
You might need to throw in a "document.location.reload();" if it isn't being picked up by google
For anyone still looking for a good solution to this, Google supports AJAX Conversions natively now through their Google Analytics API.
You can do it by making a event API call in Google Analytics. What you do is setup an Analytics event, tie it to a goal, then import that goal into AdWords as a conversion. It's a bit of a lengthy process but it's a clean solution.
Check out This Page for a tutorial
This works for me:
window.google_trackConversion({
google_conversion_id: 000000000,
conversion_label : "xxxxxxxxxxxx",
google_remarketing_only: false,
onload_callback : function(){
//do something :)
}
});

JavaScript jQuery binding

I am using jQuery to create an anchor and bind it with JavaScript function as follow:
$(document).ready
(
function()
{
var test = function(arg)
{
alert(arg);
}
var anotherTest = function(arg)
{
do something;
}
$('#id').click
(
var content = "Hello world";
var anchor = "<a href='javascript:void(0);' onclick='test(\"" + content + "\")' >test</a>";
$('#DivToBind').prepend(anchor);
);
}
);
And the problem is: the test function always alerts "a", no matter what the value of content is. If I change onclick function test to anotherTest, nothing happens but "anotherTest is not defined" appeared in the error console
Edit
To better identify my problem, I summarise my real code as follow
$(document).ready
(
function()
{
var deleteComment = function (comment)
{
commentInfo = comment.split('_');
var postid = commentInfo[0];
var enum = commentInfo[1];
var parentid = commentInfo[2];
var user = commentInfo[3];
var author = commentInfo[4];
var date = commentInfo[5];
$.get
(
"ajaxhandle.php",
{ref: 'commentdelete', pid: postid, d: date},
function(text)
{
if (text)
{
//alert(comment);
$('#' + comment).html('');
}
else
{
alert("Something goes wrong");
}
},
'text'
);
};
var test = function(arg) {alert(arg);};
$('#postCommentButton').click
(
function ($e)
{
$e.preventDefault();
var comment = $('#postdata').val();
var data = $('form#commentContent').serialize();
//alert(data);
$.post
(
"ajaxhandle.php",
data,
function($xml)
{
$xml = $($xml);
if ($xml)
{
//alert(45);
var success = $xml.find("success").text();
if (success == 1)
{
$('#postdata').val("");
var id = $xml.find("id").text();
var reference = $xml.find("reference").text();
var parentid = $xml.find("parentid").text();
var user = $xml.find("user").text();
var content = $xml.find("content").text();
var authorID = $xml.find("authorid").text();
var authorName = $xml.find("authorname").text();
var converteddate = $xml.find("converteddate").text();
var date = $xml.find("date").text();
var avatar = $xml.find("avatar").text();
comment = id + '\_wall\_' + parentid + '\_' + user + '\_' + authorID + '\_' + date;
//alert(comment);
var class = $('#wallComments').children().attr('class');
var html = "<div class='comment' id='" + comment + "' ><div class='postAvatar'><a href='profile.php?id=" + authorID + "'><img src='photos/60x60/" + avatar +"' /></a></div><div class='postBody' ><div class='postContent'><a href='profile.php?id=" + authorID + "'>" + authorName + " </a> <span>" + content + "</span><br /><div class='timeline'>Posted " + converteddate + "<br /><a href=''>Comment</a> | <a href=''>Like</a> | <a href='javascript:void(0);' onclick='deleteComment(\"" + comment + "\")' class='commentDelete' >Delete</a></div></div></div><div style='clear:both'></div><hr class='hrBlur' /></div>";
if (class == 'noComment')
{
//alert($('#wallComments').children().text());
//alert(comment);
$('#noComment').html('');
$('#wallComments').prepend(html);
}
else if(class = 'comment')
{
//alert(comment);
$('#wallComments').prepend(html);
}
}
else
{
alert("Something goes wrong");
}
}
else
alert("Something goes wrong");
},
'xml'
);
}
);
$(".comment").find('.commentDelete').click
(
function($e)
{
$e.preventDefault();
var comment = $(this).parent().parent().parent().parent().attr('id');
deleteComment(comment);
}
);
}
);
var test=... is inside a function, it's not going to be in scope on the page when you want to call it onclick the anchor.
to make it global you can leave off the var.
you could also do something like:
$(document).ready
(
function()
{
var test = function(arg)
{
alert(arg);
}
var anotherTest = function(arg)
{
//do something;
}
$('#id').click
(
function(){
var content = "Hello world";
var anchor = "<a href='javascript:void(0);'>test</a>";
$(anchor).click(function(){ test(content); });
$('#DivToBind').prepend(anchor);
});
}
);
Your example is incomplete. The call to bind click is missing a function wrapper (so it's a syntax error and won't even parse); there is no reference to calling anotherText;, and the anchor is never actually created, only a string. So it's not really possible to fix from there.
In general avoid creating dynamic content from HTML strings. As you are not HTML-escaping content, if it contains various special characters (<"'&) your script will fail and you may have a cross-site-scripting security hole. Instead, create the anchor and then write any dynamic attributes or event handlers from script:
$(document).ready(function() {
function test(arg) {
alert(arg);
}
$('#id').click(function() {
var content= 'Hello world';
$('test').click(function(event) {
test(content);
event.preventDefault();
}).appendTo('#somewhere');
});
});
It may be preferable to use a <button> styled like a link rather than a real link, since it doesn't go anywhere. A <span> styled as a link is another possibility, preferably with a tabindex attribute to make it keyboard-accessible in that case.
I think a lot of code is missing here.
But anyway, why won't you use jQuery power to bind events?
$(document).ready(function() {
var test = function(arg) {
alert(arg);
}
var anotherTest = function(arg) {
alert("another: " + arg);
}
$('#id').click(function() {
var content = "Hello world";
var anchor = $("<a href='#'>test</a>").click(function() { test(content); });
//apply anchor to DOM
});
});
I think this is what you're looking for:
$(document).ready(function() {
var test = function(arg) {
alert(arg);
};
var anotherTest = function(arg) {
alert("we did something else:" + arg);
};
$('#id').click(function() {
var content = "Hello world";
var anchor = $("<a>test</a>").click(function(event) {
event.stopPropagation();
// test(content);
anotherTest(content);
});
$('#DivToBind').prepend(anchor);
});
}
);
This example shows good use of event.stopPropagation(). Setting an anchor's href to void() or # is often a mistake.
If you're using jQuery, I would recommend using its event handler functions like so:
$(document).ready(function() {
var test = function(arg){
alert(arg);
}
var anotherTest = function(arg){
// do something;
}
$('#id').click( function(event){
var content = "Hello world";
var anchor = $("<a>test</a>");
anchor.click(function(event){
event.preventDefault(); // instead of javascript:void();
test(content);
});
$('#DivToBind').prepend(anchor);
});
});

Categories

Resources