Simon
Simon

Reputation: 11

Detecting Clicks on DIV Elements Containing Javascript?

How can you detect clicks on javascript which is fired from a <DIV>?
For example I have 3 adSense ads in 3 different <DIV>s on a page, and I want to detect and trigger an operation when an ad is clicked.

It is easy to detect clicks on<DIV> when it is empty, or with any other element; but how to detect clicks on adSense ad (code)?

Upvotes: 1

Views: 4141

Answers (3)

nemisj
nemisj

Reputation: 11980

If I would really need to achieve something like this, I would cheat a bit with the user.

Instead of trying to get click on iframe, make an overlay div and place it above iframe. Attach click event to it, and when div is clicked, hide it.

It will give the user feeling that he clicked on link, but it did not worked correctly. The second time he clicks it will already worked, cause overlay is hidden.

An example code (just for explanation purpose):

<html>
    <style>
        .test {
            position : absolute;
            top : 0;
            left : 0;
            width : 300;
            height : 300;
            z-index : 999;
            filter : alpha(opacity = 0);
            opacity : 0;
            background-color:black;
        }
    </style>
    <script>
        function start(){
            var div = document.getElementById("target");
            var source = document.createElement("div");
            source.className = "test";
            document.body.appendChild(source);

            var style = source.style;

            var div2 = document.createElement("div");
            document.body.appendChild(div2);

            source.onclick = function(e){
                style.display = "none";
                div.onmouseout = function(){
                    div2.innerHTML = "mouseout";
                    style.display = "";
                    div.onmouseout = null;
                }
                div2.innerHTML = "clicked";
            }
        }
    </script>
    <body onload="start()">
        <div id="target">
            <iframe src="http://mail.ru" style="width:300;height:300"></iframe>
        </div>

    </div>
</html>

Upvotes: 1

D.C.
D.C.

Reputation: 15588

are you using any frameworks like jQuery? if so, you could add a click handler to a child of a div:

targetElement = $("#yourDivId").children()[0]
$(targetElement).click(function(){
    alert("target element was clicked");
});

Upvotes: 2

Andy E
Andy E

Reputation: 344557

As far as I'm aware, Adsense ads are loaded in an iframe element so accessing them would be violating the same origin policy. This means you can't detect clicks in an iframe pointing to an external URL, so it can't be done.

Upvotes: 2

Related Questions