This is a project I am working on, a little popup ad for my client's website that will tell users about their summer camps coming up. I just want the ad to show up on load, and then the user can choose to close the ad or click the link to go to the registration page.
I am trying to get this code to work but my problem is that when I click one of the close buttons the ad closes, then the page reloads and the ad is right back where it was. I am trying to figure out where to appropriately place my "prevent default" code but it either works before the ad can even show up the first time, or in the case shown here... not at all.
I realize that I am using both jQuery and JS but I am very new to this and I am piecing together code as I find it.
<script type="text/javascript">
$(".close").click(function(){
$("#summercampad").addClass("hidden");
onload.preventDefault();
});
window.onload = function () {
document.getElementById("summercampad").className =
document.getElementById("summercampad").className.replace
( /(?:^|\s)hidden(?!\S)/g , '' )
};
</script>
<div id="summercampad" class="hidden" >
<div id="popupcontainer">
<div id="closepopup">
<a href="#" class="close"><img src="https://cdn6.bigcommerce.com/s-p98jqjm/product_images/uploaded_images/closebtn.png?t=1429039040" alt="close"/> </a>
</div>
<div id="pic">
<img src="https://cdn6.bigcommerce.com/s-p98jqjm/product_images/uploaded_images/popuppic.jpg?t=1429038436" alt="basketball"/>
</div>
<div id="popuptext">
2015 SUMMER CAMPS<br>
BOYS & GIRLS • ANY SKILL LEVEL<br>
<span>SPACE LIMITED - SIGN UP NOW!</span>
</div>
<div id="registerbtn" >
<a href="/camp-registration/">
<img src="https://cdn6.bigcommerce.com/s-p98jqjm/product_images/uploaded_images/registerbtn.png?t=1429039883"/>
</a>
</div>
<div id="nobtn">
<a href="#" class="close">
<img src="https://cdn6.bigcommerce.com/s-p98jqjm/product_images/uploaded_images/nothanksbtn.png?t=1429039884"/>
</a>
</div>
</div>
Just add at the end : return false. It will prevent the action to perform like you want.
<script type="text/javascript">
$(".close").click(function(){
$("#summercampad").addClass("hidden");
return false;
});
...
Everything is describe on this other post : return false from jQuery click event
You need first to declare your HTML, then your jQuery. Like you do now, $(".close") return null because HTML has not been parsed by your browser.
The best solution for you is to use $(document).ready()
Your code should be :
<script type="text/javascript">
$(document).ready(function () {
$(".close").click(function(){
$("#summercampad").addClass("hidden");
return false;
});
});
...
This way first HTML is loaded then jQuery bind a click event on existing markup ;).