I have this code in my html page:
<body>
<div align="center">
<a href="../index.html">
<img border="0" src="banner1.jpg" width="800" height="120" alt="Ecommerce Knowledge Base"> </a>
<div style="background-image:url(Heading%20Background.jpg); width:800px">
<a href="../index.html" style="position:relative; left:-130px">HOME</a>
<a href="" style="position:relative; left:-65px" id="planning">PLANNING</a>
</div>
...
...
...
</body>
The hyperlink HOME is linked to index.html page which is located in the root folder of the folder containg this html page. But nothing happens once clicking this hyperlink. Even the banner which is linked to the same page doesn’t work.
The strange thing is, both these hyperlinks were working fine before, till I made some “jquery” code changes in my page. But I’m not sure how the change is affecting this. Kindly help.
These are the code changes made from:
<script>
$(document).ready(function(){
$("#planning").click(function(e){
$("#planning_panel").slideToggle("slow");
e.preventDefault()
});
});
</script>
to:
<script>
$(document).ready(function() {
$(document).on('click',function(e) {
e.preventDefault();
var $panel = $("#planning_panel");
if (e.target.id === 'planning') {
$panel.slideToggle('slow');
} else {
$panel.slideUp('slow');
}
});
});
</script>
Both the scripts are working fine, the only problem is as soon the changes were made the hyperlinks stopped working.
This new code:
…tells the browser that when a click occurs that bubbles up to the document (as most clicks eventually do, unless you call
stopPropagationfrom a handler deeper down), the browser should prevent the default action. The default action of a click on a link is to follow the link.The solution is to only call
e.preventDefault();when you want to prevent the action of the click. Here’s how I’d probably recast that code:Live Example | Source (I’ve changed
../index.htmltohttp://stackoverflow.comon theHOMElink, but other than that the only change is the code)There we’re only preventing the default action of the click if it’s on the
#planninglink.Side note: I’ve used
closestinstead of checkinge.target.idbecause it’s more robust. It’s not strictly necessary with your markup, but if you ever changed the markup slightly (adding aspanoremor something), you’d need it, so it’s good for robustness.