Reputation: 163
I'm trying to prevent the default click action on a menu item in WordPress. I can add the class noclick to the menu item but the class is on the -li- element.
<li class="noclick"><a href="http://google.com">Google</a></li>
My first attempt was:
<script type='text/javascript'>
$('.noclick').click(function(e) {
e.preventDefault();
});
</script>
Then I realized I need to target the -a- element and I'm not sure how to do that. Any help is greatly appreciated.
Upvotes: 0
Views: 80
Reputation: 12961
Make sure your scope is safe to use $ function like:
jQuery(function($) {
...
});
then if you want to prevent the default click action on a specific menu item like that, you'd better try this:
$(".noclick>a[href*='http://google.com']")
or
$(".noclick a[href*='google.com']")
and then if you really want to prevent the all click actions then:
jQuery(function($) {
if($(".noclick>a[href*='http://google.com']").length>1){
$(".noclick>a[href*='http://google.com']")[0].onclick = function(){
return false;
}
}
else{
//it means there is something wrong with your query
}
});
this will disable all actions even if those are disregarded if you do it using jQuery e.preventDefault();
Upvotes: 0
Reputation: 318182
A LI element has no default action when you click it, the anchor has
$('.noclick a').click(function(e) {
e.preventDefault();
});
And wordpress uses noConflict mode as default, which means $ is undefined, so
jQuery(function($) {
$('.noclick a').click(function(e) {
e.preventDefault();
});
});
Upvotes: 2
Reputation: 38860
why not:
<script type='text/javascript'>
$('.noclick a').click(function(e) {
e.preventDefault();
});
</script>
this will target a
elements that are children of aelements with the class noclick
Upvotes: 0
Reputation: 388316
The only problem I see is that your code is not inside dom ready handler
jQuery(function ($) {
$('.noclick').click(function (e) {
e.preventDefault();
});
})
The click event from the a
element will get propagated to the li
element so you can register a handler for the li
element and then call preventDefault()
in that mehtod
Upvotes: 2