Reputation: 5591
I have two buttons:
<a href="#" id="A">Button-A</a>
<a href="#" id="B">Button-B</a>
And some JavaScript to trigger a click event:
jQuery("#A").click(function() {
jQuery("#B").trigger('click');
return false;
});
If Button-B
is not available (for example, on mobile, the button is not available), then Button-A
redirects user to a different page (site.com/another-page
). How can I implement this?
How can I achieve that?
Thanks
Upvotes: 1
Views: 169
Reputation: 4314
function clickHandler(e){
var $btn = $("#B").trigger('click');
if(!$btn.length)
window.location = 'site.com/another-page';
e.preventDefault();
}
$("#A").click(clickHandler);
Upvotes: 0
Reputation: 5636
Check if the element exists and then add the event listener
$(function(){
if($("#B").length) { // the element exists
jQuery("#A").click(function(){
jQuery("#B").trigger('click');
return false;
});
} else { // element doesn't exist, add a different listener
jQuery("#A").click(function(){
window.location = "http://newurl.com";
});
}
});
Upvotes: 2
Reputation: 388326
You can check the length of the jQuery object to see whether it exists
jQuery("#A").click(function () {
var $btn = jQuery("#B").trigger('click');
if(!$btn.length){
window.location = 'new location'
}
return false;
});
Upvotes: 2