11

I'm working on something for a client and an agency have built a small bit of jQuery to fire off a DoubleClick Floodlight Tag but for some reason the tag doesn't work:

<script type="text/javascript">
$(function () {

    //var origOnClick = $('#trackingButton').attr("onclick");
    $('#trackingButton').click(fireFloodlight);
    function fireFloodlight() {
        if (Page_IsValid) {
            var axel = Math.random() + "";
            var a = axel * 10000000000000;
            $("body").append('<img src="https://ad.doubleclick.net/activity;src=2499215;type=axa_l124;cat=lpg_g263;ord=' + a + '?" width="1" height="1" alt=""/>');
            //eval(origOnClick);
        }
    }

});
</script>

To me this script looks fine, but in a live environment the call to "ad.doubleclick.net" is never made? Any help would be much appreciated. Strangely the tag was working until this weekend but now is not recording any actions?

EDIT: I did a console.log(Page_IsValid) which returned True.

EDIT: Here is the HTML for the button in question:

<input type="submit" name="ctl00$ctl00$ctl00$BodyPlaceHolder$BodyPlaceHolder$WizardContentPlaceHolder$WizardCollectBasicSMEInfo$trackingButton" value="Get your quick quote" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$ctl00$ctl00$BodyPlaceHolder$BodyPlaceHolder$WizardContentPlaceHolder$WizardCollectBasicSMEInfo$trackingButton&quot;, &quot;&quot;, true, &quot;Form&quot;, &quot;&quot;, false, false))" id="trackingButton" class="button" />
zik
  • 3,035
  • 10
  • 41
  • 62

8 Answers8

6

You already have the function on document ready, your problem is that you are calling the function in a wrong way, if you want to call the function like that you should declare it as a function expression (see Function Expressions in this link for more info):

$(function () {

var fireFloodlight = function()  {
    if (true) {
        var axel = Math.random() + "";
        var a = axel * 10000000000000;
        $("body").append('<img src="http://tejedoresdesuenos.com.mx/wp-content/uploads/2011/06/google.jpg" width="50" height="10" alt=""/>');
        alert('ello');
    }
}

$('#trackingButton').click(fireFloodlight);


});

a working example.

KoU_warch
  • 2,160
  • 1
  • 25
  • 46
  • my apologies for not getting back to anyone sooner but I've been out of the country. What you said was correct, it was indeed because it needed to be declared as a function expression. – zik Dec 03 '12 at 15:02
3

If this code is in the head tag of your HTML file it will not work properly. The JavaScript will try to execute before the page is finished being rendered. Because of this, when the code executes, the input tag will not exist yet according to the parser. You can put it in a document ready function or you can simply put your script tag at the end of the HTML document (before the end body tag).

<script type="text/javascript">
    $(document).ready(function () {
        $('#trackingButton').click(fireFloodlight);
        function fireFloodlight() {
            if (Page_IsValid) {
                var axel = Math.random() + "";
                var a = axel * 10000000000000;
                $("body").append('<img src="https://ad.doubleclick.net/activity;src=2499215;type=axa_l124;cat=lpg_g263;ord=' + a + '?" width="1" height="1" alt=""/>');
            }
        }
    });
</script>

Also, unless you're using the fireFloodlight function in other onclick functions, you can just pass it in as an anonymous function.

<script type="text/javascript">
    $(document).ready(function () {
        $('#trackingButton').click(function() {
            if (Page_IsValid) {
                var axel = Math.random() + "";
                var a = axel * 10000000000000;
                $("body").append('<img src="https://ad.doubleclick.net/activity;src=2499215;type=axa_l124;cat=lpg_g263;ord=' + a + '?" width="1" height="1" alt=""/>');
            }
        });
    });
</script>

On top of that, if you're using the latest version of jQuery, you'll want to use .on() instead of .live(), .delegate(), or .click(). The former two are now technically deprecated in the latest version of jQuery (although I highly doubt they'll be removed for some time) and, if I remember correctly, .click() is simply a wrapper for the .on(), so it's technically faster to just use .on().

I'll give you two examples of how to use .on().

The first example is for simply adding the event to the #trackingButton element after the page has been loaded initially.

<script type="text/javascript">
    $(document).ready(function () {
        $('#trackingButton').on('click',function() {
            if (Page_IsValid) {
                var axel = Math.random() + "";
                var a = axel * 10000000000000;
                $("body").append('<img src="https://ad.doubleclick.net/activity;src=2499215;type=axa_l124;cat=lpg_g263;ord=' + a + '?" width="1" height="1" alt=""/>');
            }
        });
    });
</script>

The second example here works by attaching the event to a parent element and executing the function after it bubbles up the DOM to the parent element, and the target element matches the selector provided in the second parameter. It is typically used when attaching events to elements that may be added/removed/re-added to the page dynamically after the initial load.

<script type="text/javascript">
    $(document).ready(function () {
        $(document).on('click','#trackingButton',function() {
            if (Page_IsValid) {
                var axel = Math.random() + "";
                var a = axel * 10000000000000;
                $("body").append('<img src="https://ad.doubleclick.net/activity;src=2499215;type=axa_l124;cat=lpg_g263;ord=' + a + '?" width="1" height="1" alt=""/>');
            }
        });
    });
</script>

I hope these examples help!

Swivel
  • 3,020
  • 26
  • 36
  • 2
    Amazing, thanks for your help. The code isn't in the `` but is rather a little further down after the `` tag. I'm gonna give your 3rd bit of code a whirl and will let you know... – zik Oct 31 '12 at 09:43
  • 2
    Hi mate, just waiting on someone to get back to me. But it's looking good! Will update you soon! – zik Nov 01 '12 at 17:11
3

Try this:

        //var origOnClick = $('#trackingButton').attr("onclick");
        $('#trackingButton').live("click", function(){

            if (Page_IsValid) {
                var axel = Math.random() + "";
                var a = axel * 10000000000000;
                $("body").append('<img src="https://ad.doubleclick.net/activity;src=2499215;type=axa_l124;cat=lpg_g263;ord=' + a + '?" width="1" height="1" alt=""/>');
                //eval(origOnClick);
            }
         });
Relentless
  • 122
  • 6
2

You have actually assigned two event handlers for the same event, to the same element. As far as I know that should not be possible.

Also, you should wrap your function call inside an anonymous function, like this:

$('#trackingButton').click( function() {

    fireFloodlight();

});

You may want to avoid assigning event handlers directly in the HTML markup, it's generally considered a bad practice.

Make sure your #trackingButton is already present in the DOM when you call try to assign it the click event handler.

Also make sure that there are no errors in the console log, and that no other plugins or scripts are modifying the DOM when you try to assign your event handler.

Jose Faeti
  • 12,126
  • 5
  • 38
  • 52
  • 2
    There is nothing wrong with attaching multiple listeners for the same event on the same element in modern browsers (it has been supported _at least_ since the IE5.5 era), though not when mixing HTML event attributes and JS event attachment, but your comment is still at least misleading; also your suggestion to wrap a plain function reference in an _additional_ function makes absolutely no sense, and you provide no reasoning for it. – lanzz Oct 30 '12 at 13:11
2

Your html node has an explicit onclick attribute, which, according to your code, is not deactivated.

What does WebForm_DoPostBackWithOptions do ? If, in some configuration, this function returns false, it will prevent the other handlers from being called.

If you can act on the code which produces the html, I would advise to remove this onclick attribute from the node, and declare it as a jquery click handler.

LeGEC
  • 46,477
  • 5
  • 57
  • 104
2

This code fires both, the onclick event as well as the click event bound to the #trackingButton selector :

You can move the onclick event to fire a function rather than having it inline :

<input type="submit" onclick="myPostBack()" name="ctl00$ctl00$ctl00$BodyPlaceHolder$BodyPlaceHolder$WizardContentPlaceHolder$WizardCollectBasicSMEInfo$trackingButton" value="Get your quick quote" id="trackingButton" class="button" />

.... then the js :

function myPostBack() {
/*
    WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ctl00$ctl00$BodyPlaceHolder$BodyPlaceHolder$WizardContentPlaceHolder$WizardCollectBasicSMEInfo$trackingButton", "", true, "Form", "", false, false))
*/
    alert("postback executed")
}

Note: I set an alert as an example to verify that the myPostBack function is executed.

If WebForm_DoPostBackWithOptions is not exectuded, check that you don't have syntax errors (using &quot; triggers js errors) and you pass the right parameters ... check this for more.

...js (continue)

function fireFloodlight() {
    if (Page_IsValid) {
        var axel = Math.random() + "";
        var a = axel * 10000000000000;
        $("body").append('<img src="https://ad.doubleclick.net/activity;src=2499215;type=axa_l124;cat=lpg_g263;ord=' + a + '?" width="1" height="1" alt=""/>');
        //eval(origOnClick);

        // append another image for verification purposes
        $("body").append('<img src="http://www.devaldi.com/wp-content/uploads/2009/10/jquery-logo.gif" alt="jquery" />')
    }
}

$(function() {
  // using .on() requires jQuery 1.7+
    $('#trackingButton').on("click", function() {
        fireFloodlight();
    });
});

Assuming that Page_IsValid is true, that should work ... SEE JSFIDDLE example ... if everything goes right you should see the postback alert as well as the jQuery image ;)

JFK
  • 40,963
  • 31
  • 133
  • 306
1

How do you add your #trackingButton? If you're doing it by jQuery, use on instead of click

 $('body').on('click','#trackingButton',function(){
      console.log("Page_IsValid: "+Page_IsValid);
      if (Page_IsValid) {
        var axel = Math.random() + "";
        var a = axel * 10000000000000;
        $("body").append('<img src="https://ad.doubleclick.net/activity;src=2499215;type=axa_l124;cat=lpg_g263;ord=' + a + '?" width="1" height="1" alt=""/>');
      }
    });

Page_IsValid should be true, and your img should be added to the DOM.

Did it work?

Marek Karbarz
  • 28,956
  • 6
  • 53
  • 73
Munchies
  • 444
  • 6
  • 14
  • 1
    It's not added via jQuery. It's just an `` button with `type=submit`. – zik Oct 25 '12 at 11:26
  • Even then, delegate is deprecated in the latest version of jQuery. `.on()` should be used, as in my examples. If you would like to delegate your events, you can use `$('PARENT SELECTOR').on('EVENT NAME','TARGET SELECTOR',function(){/* CALLBACK */});` otherwise you use `$('TARGET SELECTOR').on('EVENT NAME',function(){/* CALLBACK */});` :P – Swivel Oct 31 '12 at 14:55
1

It's possible that the submit button is firing a request, so you never get to see the image being added to the body. event.preventDefault() might fix this.

$('#trackingButton').click(function(event) {
    event.preventDefault();
    if (Page_IsValid) {
        var axel = Math.random() + "";
        var a = axel * 10000000000000;
        $("body").append('<img src="https://ad.doubleclick.net/activity;src=2499215;type=axa_l124;cat=lpg_g263;ord=' + a + '?" width="1" height="1" alt=""/>');
        //eval(origOnClick);
    }
}
LukeGT
  • 2,324
  • 1
  • 21
  • 20