Reputation: 42967
I have a problem with a very simple JavaScript pop-up script.
I have this example page: http://www.onofri.org/example/example4/
At the end of this page there is a box containing some flags including the British flag that is reprsented by the #reportEng div
(inside the engLink link).
What I want is that when the user clicks on this element a pop0up message will show.
So I have add to the page this simple script:
<script>
var test = document.getElementById('engLink');
test.addEventListener('click', function() {
alert('clicked');
});
</script>
I have put the script inside the body section of the page and not in the head section because this is only a test page and the final result will be put into a page of a CMS in which I do not have access to the template (so I can't put the script in the head section).
The problem is that it does not work. If I click on the English flag the page is reloaded and the pop-up not shown.
Can you help me?
Thank you,
Andrea
Upvotes: 0
Views: 80
Reputation: 1516
You are using a <a> tag, change it to use a <div> tag, or remove <a> tag at all
You can follow this to make div clickable.
Upvotes: 0
Reputation: 1391
I went a completely different approach. The addEventListener is pretty cool, but I'm a bit OLD and I've defaulted to nasty habits. This works just fine for me.
<script>
function myExample(){
alert("BaZing! It works!");
}
</script>
And for the HTML part...
<a href="" id="engLink"><div id="reportEng" onClick="myExample()"></div></a>
I also want to point out that this 'fix' is a bit taboo (see here)
Upvotes: 2
Reputation: 12139
You don't prevent the link from being followed, so when you click the link which has an empty href
, you simply reload the current page.
There are many ways to prevent the defaul link behaviour, but here is the old school way:
<a href="javascript:void(0);" id="engLink"><div id="reportEng"></div></a>
Also on a side note I don't think a div
element is allowed inside an a
in HTML or XHTML.
Upvotes: 0