I want to attach a jQuery event handler to a <div>
element such that whenever a link is clicked which points to this <div>
, that handler is activated and the associated function is executed – regardless of the location of the link (same page, other page, other site) pointing to the <div>
.
$("div#mydiv").on("linked_to", function(){ //is there a "linked_to" event?
//do something about it
});
Is this possible? Can scrollIntoView()
be used?
What you want is quite specific and borderline undoable. I think your best bet is to detect a hash change in the URL and act accordingly.
You aren't gonna be able to detect that div#mydiv
itself was clicked, but detecting the hash #mydiv
comes pretty close to it.
You would use something like:
window.onhashchange = function() {
if (window.location.hash === '#mydiv') { // here you check if it was `#mydiv`
alert('hey! are you after mydiv?!')
}
}
Check an example here: http://output.jsbin.com/pikifov - click the link and notice how the hash from the URL changes.
Source for the JSBin above here .
Full code:
<div id="mydiv">mydiv</div> <hr> <a href="#mydiv">Click to go to mydiv</a> <script> window.onhashchange = function() { if (window.location.hash === '#mydiv') { alert('hey! are you after mydiv?!') } } </script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.