Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  49] [ 2]  / answers: 1 / hits: 32685  / 11 Years ago, fri, october 4, 2013, 12:00:00

With the following jQuery based script you can stop the default action of dummy links, ie: <a href=#>



$('a').click(function(e) {
e.preventDefault();
});


What would be the plain vanilla version of this script?



I'm not a JavaScript programmer but I'm thinking it may be something that uses return false;. Again, I may be totally wrong.



Thanks in advance for your help.


More From » jquery

 Answers
6

You have event.preventDefault() available in vanilla javascript as well. In a generic way you can always use return false. If you attach an event handler you are guaranteed to get event agument passed in the handler as opposed to using the onclick or any other attributes of the element (In which case you should rely on the specific event object available in side the handler which you may not get in all browsers, like in IE you would use window.event).



Ex: -



  document.getElementById('someId').addEventListener('click', function(e){ //say this is an anchor
//do something
e.preventDefault();
});


So for all the anchors:



 var anchors = document.getElementsByTagName('a');
for(i=0, len=anchors.length; i<len; i++){
anchors[i].addEventListener('click', function(e){e.preventDefault();});
}

[#75238] Thursday, October 3, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cruzs

Total Points: 710
Total Questions: 113
Total Answers: 100

Location: Nepal
Member since Sat, Jul 18, 2020
4 Years ago
cruzs questions
Thu, Nov 26, 20, 00:00, 4 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Wed, Aug 19, 20, 00:00, 4 Years ago
Sun, Aug 2, 20, 00:00, 4 Years ago
;