JQuery get hash of <a> element using .on () event
Before I start flashing links with reference manuals, I have been doing this for quite some time and continue the dead end. I'm not even sure how to properly debug it. Therefore, if links are provided, please make sure that they are well commented and instructed. This is because I am a PHP / mySQL developer, and the reference model of the JavaScript object is a bit confusing for me (but definitely trying to learn! :)).
I am trying to update my jQuery knowledge with jQuery v1.7.2. Apparently, the live event was deprecated and replaced with .on (). JQuery docs say you can't mix old 'click' or 'live' events with any scripts using .on ().
When trying to get used to it, I try to grab the hash of the given URL.
The page looks like this (the header is already loaded by jquery.min.1.7.2.js):
<div id='menuHolder' style="position:relative; margin-left:50px;margin-bottom:30px; padding-top:35px; min-width:600px;z-index:998;"> <ul id="menu"> <li><a href="#">Events</a> <ul id="events"> <li> <img class="corner_inset_left" alt="" src="images/menu/corner_inset_left.png"/> <a id="linker21 menu" class="test AJAXcaller" href="index.php#?p=1&d=AJAXcontent&i=1&k=<?=$_SESSION['authcpanel']['key']?>" rel="nofollow">Upcoming Events</a> <img class="corner_inset_right" alt="" src="images/menu/corner_inset_right.png"/> </li> <li><a href="#">List All Events</a></li> <li><a id="linkermenu" class="test AJAXcaller" href="index.php#?p=24&d=AJAXcontent&i=1&k=<?=$_SESSION['authcpanel']['key']?>" rel="nofollow">Add Events</a></li> <li class="last"> <img class="corner_left" alt="" src="images/menu/corner_left.png"/> <img class="middle" alt="" src="images/menu/dot.gif"/> <img class="corner_right" alt="" src="images/menu/corner_right.png"/> </li> </ul> </li> </ul> </div> <script> $(document).on("click", "a.AJAXcaller", function(){ alert("Goodbye!"); alert($(this).attr("hash")); }); </script> The first warning is triggered when you click on the link "Add Events" (which has a hash), the relay "Goodbye!", Then the second handler starts the relay "undefined". How do I access this hash?
My old code is as follows and it works, but any ajax-related pages will not be attached by event handlers, so I use the .on () event. Also, if I'm going to learn how to do this, this time;), I don't need legacy functions ...
OLD CODE (works)
var linkClickAction = { 'a.AJAXcaller' : function(element){ element.onclick = function(){ var locationString = $(this).attr("hash"); locationString = locationString.replace(/.*\#(.*)/, "$1") var parameterString = locationString.replace(/.*\?(.*)/, "$1"); // onclick="sndReq('j=1&q=2&t=127.0.0.1&c=5'); var parameterTokens = parameterString.split("&"); // onclick="sndReq('j=1,q=2,t=127.0.0.1,c=5'); var parameterList = new Array(); for (j = 0; j < parameterTokens.length; j++) { var parameterName = parameterTokens[j].replace(/(.*)=.*/, "$1"); // j var parameterValue = parameterTokens[j].replace(/.*=(.*)/, "$1"); // 1 parameterList[parameterName] = parameterValue; } var page = parameterList['p']; var key = parameterList['k']; var includesDir = parameterList['i']; var changeDiv = parameterList['d']; sndReq(page,key,includesDir,changeDiv,parameterString); return false; } } }; Behaviour.register(linkClickAction); A behaviour.js script file was also uploaded that mainly handled the listener. At that time, I did not use jQuery at all. It was nice, and FAST (tiny .js files, without extraneous code), comparatively speaking, but I hit my limit on being able to write effective JavaScript when it came to handling fancy things in my ui. Therefore, I have to load the jQuery script when the page loads. After seeing how it is already loaded, I try to use it instead of adding additional noecesarry scripts to load my page. So I want to find a result that uses jQuery 1.7.2 native functions to achieve this.
results
It turns out that jQuery 1.6+ can break when using .attr () to find the property of the DOM object. So using .prop () is the way to go. The corrected code is as follows:
/* Page: rating.js Created: Aug 2006 Last Mod: May 30, 2012 Modder: Darren Maurer */ function sndReq(page,key,includesDir,changeDiv,parameterString) { var divToChange = document.getElementById(changeDiv); // the Div that the data will be put into // switch Div with a loading div divToChange.innerHTML = '<div class="loading"><img src="images/loading.gif" title="Saskatoon.CityGuru.ca - Loading Page" alt="Saskatoon.CityGuru.ca - Loading Page" border="0"/></div>'; if (includesDir == 1){ //Find Current Working Directory. Use to find path to call other files from /*var myloc = window.location.href; var locarray = myloc.split("/"); delete locarray[(locarray.length-1)]; var arraytext = locarray.join("/"); */ $.ajax({ type: "POST", url: "AJAXCaller.php", data: parameterString, success: function(msg){ $('#'+changeDiv).html(msg); } }); } } /* =======END AJAX FUNCTIONS================= */ /* =======BEGIN CLICK LISTENER FUNCTIONS================= */ /* Listens to any a href link that has a class containing ' AJAXcaller' */ /* ie. <a id="link1" class="test AJAXcaller" href="index.php#http://233.help?id=22&think=33" rel="nofollow">> AJAX TEST LINK <</a> */ $(document).on("click", "a.AJAXcaller", function(){ alert($(this).prop("hash")); var locationString = $(this).prop("hash"); locationString = locationString.replace(/.*\#(.*)/, "$1") var parameterString = locationString.replace(/.*\?(.*)/, "$1"); // onclick="sndReq('j=1&q=2&t=127.0.0.1&c=5'); var parameterTokens = parameterString.split("&"); // onclick="sndReq('j=1,q=2,t=127.0.0.1,c=5'); var parameterList = new Array(); for (j = 0; j < parameterTokens.length; j++) { var parameterName = parameterTokens[j].replace(/(.*)=.*/, "$1"); // j var parameterValue = parameterTokens[j].replace(/.*=(.*)/, "$1"); // 1 parameterList[parameterName] = parameterValue; } var page = parameterList['p']; var key = parameterList['k']; var includesDir = parameterList['i']; var changeDiv = parameterList['d']; sndReq(page,key,includesDir,changeDiv,parameterString); return false; }); Hope this helps someone, it was definitely a salvation for me!
Your item has no hash attribute. try to get the href attribute and use the javascript substr and indexOf functions to split the string into #
var href = $(this).attr("href"); var hash = href.substr(href.indexOf("#")); You can also use
$(this).prop("hash"); $('a.js-hash').click(function() { // Store hash var hash = this.hash; // Using jQuery animate() method to add smooth page scroll $('html, body').animate({ scrollTop: $(hash).offset().top }, 1000, function() { // Add hash (#) to URL when done scrolling (default click behavior) window.location.hash = hash; }); // Prevent default anchor click behavior return false; });