1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Javascript to show ad code based on browser window size

Discussion in 'JavaScript' started by asabet, Nov 24, 2015.

  1. #1
    I have two ads.

    This one is a 728x90 Amazon ad:

    <script type="text/javascript" language="javascript" src="//c.amazon-adsystem.com/aax2/getads.js"></script>
    <script type="text/javascript" language="javascript">
    //<![CDATA[
    aax_getad_mpb({
      "slot_uuid":"123456789-123456789"
    });
    //]]>
    </script>
    Code (markup):
    And this one is a 320x50 Adsense ad:

    
    <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
    <!-- small_leader -->
    <ins class="adsbygoogle"
         style="display:inline-block;width:320px;height:50px"
         data-ad-client="ca-pub-123456789"
         data-ad-slot="123456789"></ins>
    <script>
    (adsbygoogle = window.adsbygoogle || []).push({});
    </script>
    
    Code (markup):
    I want a javascript that will show the Amazon ad when the browser window is more than 728px wide and the Adsense ad when the browser window is less than or equal to 728px wide.

    I know how to accomplish this using CSS with display:none, but that violates the terms of the Amazon ad network, so I'm looking for a javascript solution that won't call the ad unless it is showing.

    Would appreciate any help.

    Thanks,
    Amin
     
    Solved! View solution.
    asabet, Nov 24, 2015 IP
  2. Webpass.io

    Webpass.io Member

    Messages:
    8
    Likes Received:
    2
    Best Answers:
    1
    Trophy Points:
    33
    #2
    I'm not easily able to test solutions for you, but the following may be of help. Using jquery, you can check the window size and conditionally do stuff:

    <!doctype html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Demo</title>
    </head>
    <body>
        <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
        <script>
            if ($(window).width() > 728) {
                // Wider browser
            } else {
                // Thinner browser
            }
         </script>
    </body>
    </html>
    HTML:
    Use $(window).width() to get the browser viewport width, and $(document).width() to get the HTML document width.

    Then you can try conditionally loading scripts. Perhaps you will be able to use:

    http://api.jquery.com/jQuery.getScript/

    It may not matter if you include the html for both scripts, and just set it hidden with something like display:none, as long as the javascript file itself isn't retrieved by the browser.
     
    Webpass.io, Nov 27, 2015 IP
  3. asabet

    asabet Active Member

    Messages:
    125
    Likes Received:
    38
    Best Answers:
    0
    Trophy Points:
    90
    #3
    asabet, Nov 28, 2015 IP
  4. #4
    Here you go buddy, try this! (pure javascript, no jquery dependency!)

    
    <div id="responsiveUnit"></div>
    <script>
        var ra_w = Math.max(document.documentElement["clientWidth"], document.body["scrollWidth"], document.documentElement["scrollWidth"], document.body["offsetWidth"], document.documentElement["offsetWidth"]);
        if( ra_w > 728 )
        {
            var se = document.createElement('script');
            se.type = "text/javascript";
            se.src = (document.location.protocol === "https:" ? "https:" : "http:") + "//c.amazon-adsystem.com/aax2/getads.js";
            var script = document.getElementById('responsiveUnit').appendChild(se);
            script.onload = function() {
                //<![CDATA[
                aax_getad_mpb({
                 "slot_uuid":"123456789-123456789"
                });
                //]]>
            };
        }
        else
        {
            var se = document.createElement('script');
            se.type = "text/javascript";
            se.src = (document.location.protocol === "https:" ? "https:" : "http:") + "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
            document.getElementById('responsiveUnit').appendChild(se);
          
            var ins = document.createElement('ins');
            ins.setAttribute('class', "adsbygoogle");
            ins.setAttribute('style', "display:inline-block;width:320px;height:50px");
            ins.setAttribute('data-ad-clent', "ca-pub-123456789");
            ins.setAttribute('data-ad-slot', "123456789");
            document.getElementById('responsiveUnit').appendChild(ins);
          
            (adsbygoogle = window.adsbygoogle || []).push({});
        }
    </script>
    
    HTML:
     
    AdConjure, Dec 17, 2015 IP
  5. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #5
    Since you're using google ads, why not just use the new Responsive adverts section and let them decide the proper size to show based on the container?

    Really looks like most of your code is just dicking around for no good reason when Google is already providing this through data-ad-format="auto"

    Lifted straight off my current site:
    <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
    <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-123456789" data-ad-slot="123456789" data-ad-format="auto"></ins>
    <script>(adsbygoogle = window.adsbygoogle || []).push({});</script>';
    Code (markup):
    Easy-peasy. They'll chose a random ad that fits whatever the available width of the container that INS tag is inside when the page loads. VERY handy since my wrappers are in EM so who knows what the resulting pixel size MIGHT be... they'll pick whatever fits best from all their sizes!

    I do wish they hooked onresize to load a new image if the window size is changed, that CAN bite you but in that case just set the parent to overflow:hidden to chop off if it's too big. I'm playing with that to see if I can delete the ins tag, pop it's corresponding object index, and push a new one.

    WAY easier. Just skip dicking with the width and height, and just set data-ad-format to auto. Set whatever element it's inside (like a column or style wrapper) to whatever width you want, and it will load the correct one on page-load.

    The lack of responsive ad code was one of the many things (alongside my utter and complete distrust of the sleazeball scam artists known as adverisers) that was preventing me from even considering putting ads on a site. As it is my putting it on my latest site is more of an experiment than actually looking for revenue out of it.

    ... and as always, when someone suggests "use jQuery" they don't know enough about what's going on to even be flapping their gums on the subject. Halfwit nonsense at best.
     
    deathshadow, Dec 17, 2015 IP
  6. AdConjure

    AdConjure Active Member

    Messages:
    57
    Likes Received:
    5
    Best Answers:
    1
    Trophy Points:
    65
    #6
    While you are correct, Google Adsense does now offer responsive ads, using just one advertising company to handle all the ads on your website is amateur level monetizing.

    Serving the right ads to the right traffic is the name of the game. Working with multiple companies and displaying them to the right visitors maximizes revenue without-a-doubt.

    And IMO, the above code is a good contribution to have floating around the internet for anyone who wants to play with making their own responsive ad units for ad networks that don't currently support them!
     
    AdConjure, Dec 17, 2015 IP
  7. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #7
    You want to make it better? check the size of the ELEMENT around the ad to set the values after "onload" fires. Let CSS size the element however it wants, have the script once styling has been applied handle the image scale. The determining factor shouldn't be the window size, it should be the area allocated to allowing an advertisement's width (and/or height, though I prefer auto in that behavior) -- in the (broken) code you provided that would be (div#responsiveUnit).clientWidth as what should be making the decision!

    Trapping onresize might be good too to swap/reload the advert -- as I think I already mentioned.
     
    deathshadow, Dec 17, 2015 IP
  8. AdConjure

    AdConjure Active Member

    Messages:
    57
    Likes Received:
    5
    Best Answers:
    1
    Trophy Points:
    65
    #8

    Look buddy, not trying to go back and forth with you via the internet. This man asked a question in which I gave him the answer to. He did not ask for advice. He asked how to accomplish something. I hope you have a good day and that the above code doesn't take too much of your sleep!
     
    AdConjure, Dec 18, 2015 IP
  9. asabet

    asabet Active Member

    Messages:
    125
    Likes Received:
    38
    Best Answers:
    0
    Trophy Points:
    90
    #9
    Thank you very much!
     
    asabet, Dec 18, 2015 IP
  10. AdConjure

    AdConjure Active Member

    Messages:
    57
    Likes Received:
    5
    Best Answers:
    1
    Trophy Points:
    65
    #10
    No problem, let me know ever need anything else js/ad related!
     
    AdConjure, Dec 18, 2015 IP
  11. AdConjure

    AdConjure Active Member

    Messages:
    57
    Likes Received:
    5
    Best Answers:
    1
    Trophy Points:
    65
    #11
    I think the reason they don't offer this is that either A. advertisers would then need to provide a banner for every size google offers or B. they would have to query a new ad on window resize which would be bad practice.

    The same with the code I provided above, if I were to bind to window resize then it would query adsense for a new ad every time the window was resized. Take a website being viewed on mobile, in that case if you were to rotate the phone you would get 4 ad impressions per full rotation. Adsense may not be too happy about that.
     
    AdConjure, Dec 18, 2015 IP