Reputation: 15
So I have some images that are positioned absolutely above a page set to hidden that display inherit when you click on the appropriate link triggering the event that displays them.
Now, here's where my question comes in. Say I assign an image an ID of "example" - is there any way that when someone enters the site with a hash tag #example or clicks on a link with the hash tag #example in the url, that the event would trigger for an image with the same ID? I'm really stumped on this one
What I had been using is this:
$("#activate1").click(function () {
$("#flyer1").css("display", "inherit");
});
Which worked fine but now I'll have to add flyers each week which would mean I need to change that unless I want to write the above code for each unique case. But on top of that, I also now have to send them to people through a link so the script now has to trigger when they click the link - I figured the best way to tackle this would probably be implementing a hash tag trigger
Upvotes: 1
Views: 1314
Reputation: 708016
To activate all the links in the page that have a hash tag in them without coding for any specific names, you can do this:
$('a[href*="#"]').on('click', function(e) {
var match = this.href.match(/#[^#]+$/);
if (match) {
// trigger a click on the object that has an id
// matching the hash value in the link
$(match[0]).trigger('click');
return(false); // no default processing for the link
}
});
To process the hash tag on the initial link, you could run this code:
$(document).ready(function() {
if (window.location.hash && window.location.hash != "#") {
$(window.location.hash).trigger('click');
}
});
Upvotes: 2
Reputation: 11132
Plugins are your friend. A quick Google shows that Ben Alman's jQuery BBQ library can lead you a helpful hand!
(unrelated: jQuery libraries with cool names are an awesome addition to your future projects!)
Upvotes: 0
Reputation:
$(function() {
$('#example').on('click', function() {
alert('was triggered');
});
$(window.location.hash).trigger('click');
});
Upvotes: 4