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.
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();});
}
// Like $('a'), gets all the <a> elements in the document.
var aElements = document.getElementsByTagName('a');
// Create one function object instead of one per <a> element.
// The calling convention is the same for jQuery as for regular JS.
function preventDefaultListener(e) { e.preventDefault(); }
// For each a element,
for (var i = 0, n = aElements.length; i < n; ++i) {
// register the listener to be fired on click.
aElements[i].addEventListener('click', preventDefaultListener);
}
Return false is the way to go. E.g. if your anchor already has an href:
Click me
calling onclick like this will only perform the function, but not the navigation.
yes you can use return false;
test
#Ricardo you are correct sir.
Not only does return false disable the default action for a said element, it prevents bubbling also.
e.preventDefault();
e.stopPropagation();
is equal to
return false;
you decide :)
Related
this is my anchor i am using in CodeIgnitor pagination.
2
now this is the definition of function in Javascript
function myFunction(e){
console.log(e);
e.preventDefault()
}
Now e is an anchor which is shown in the console. but when i try
e.preventDefault()
it gives me this error.
e.preventDefault is not a function
and obviously page redirected which is original problem i want to solve. i do not want it to redirect.
You're passing the value of this which is the <a> element object, not the event object.
You could pass event instead, but you really should avoid using intrinsic event attributes (which have a bunch of gotchas) and switch to addEventListener.
const links = document.querySelector('[data-ci-pagination-page]');
for (let i = 0; i < links.length; i++) {
links[i].addEventListener(myFunction);
}
Since you've written onclick="myFunction(this)" you pass this as an argument, where this is your <a> element.
Try passing the event instead: onclick="myFunction(event)"
this seems to work like a charm:
function myFunction(event){
event.preventDefault();
}
2
This is the jQuery code I have
$('p').click(function(){
alert("click successful!");
});
This is the JS code I could come up with
window.onload = function() {
var para = document.getElementsByTagName('p');
for(var i = 0; i < para.length; i++) {
para[i].addEventListener('click',function(){
alert("click successful!");
});
}
}
The Javascript code is too bulky, is there a way where I can select a tag by its name and write the code as -
"If any 'p' tag is clicked, alert('click successful')"
instead of looping through all the <p></p> tags?
Any alternative way using tag name?
You can use event delegation - add a click handler to a higher level element and check event.target
document.body.addEventListener("click", function(e) {
if (e.target.tagName.toLowerCase() == "p") alert("click succeeded");
});
Demo: http://jsfiddle.net/jdkr3sch/
jQuery is "less code" because you're calling a pre-written function. Don't want to use jQuery? Then write your own functions.
function addEventToElements(tagname,handler) {
var elems = document.getElementsByTagName(tagname);
for(var i = 0, l = elems.length; i<l; i++) {
elems[i].addEventListener('click',handler);
}
}
Now in your actual code, you can just write:
addEventToElements('p',function() {alert("click succeeded");});
Congratulations, you have re-invented jQuery.
... Or not, because the reason jQuery is so popular is that it does a lot more. Things like normalising browser support (for those that use attachEvent or the old onEventName handlers) are half the reason jQuery exists, and you'd have to account for all of them in your own re-invention ;)
Here's a shorter way.
document.addEventListener('DOMContentLoaded', function() {
document.body.addEventListener('click', function(evt) {
if (evt.target.matches('p, p *')) alert('Paragraph clicked!');
}, false);
}, false);
Notes:
1) This has the advantage of event delegation, which is something I'd suggest looking into. In a nutshell, means you bind the event once, not N times, and then interrogate which element fired it when it fires, i.e. in the callback, not at the point of declaring the event as you are currently.
2) For waiting to use elements, use the DOMContentLoaded event rather than window.onload - the former is (loosely) analogous to jQuery's DOM ready handler.
3) matches() is a relatively modern method and won't work in ancient browsers, or may need a vendor-prefixed version - http://caniuse.com/#feat=matchesselector
for selecting:
document.querySelectorAll('p')
(also for more than one element p ).
AFAIK this is the closest thing to $('p')
addEventListener('click',function(){alert("click successful!")}
to add click handler to single element.
to simulate an array you can use the [].slice.call on the dom element collection (in this way you use .forEach() method) .
all together:
[].slice.call(document.querySelectorAll('p')).
forEach(function(x){x.addEventListener('click',
function(){alert("click successful!")
})})
https://jsfiddle.net/maio/m861hbmh/
I updated my code and rephrased my question:
I am trying to create the following condition. When a link with an empty href attribute (for example href="") is clicked, a modal is launched and the default behavior of that link is prevented..
But when the href attribute contains a value (href="www.something.com") I would like for the link to work as it normally does using its default behavior.
For some reason my code isn't working. Any help is appreciated.
// Semicolon (;) to ensure closing of earlier scripting
// Encapsulation
// $ is assigned to jQuery
;(function($) {
// DOM Ready
$(function() {
// Binding a click event
// From jQuery v.1.7.0 use .on() instead of .bind()
$('.launch').bind('click', function(e) {
var attrId = $(this).attr('attrId');
if( $('.launch').attr('href') == '') {
// Prevents the default action to be triggered.
e.preventDefault();
// Triggering bPopup when click event is fired
$('div[attrId="' + attrId+'"]').bPopup({
//position: ['auto', 'auto'], //x, y
appendTo: 'body'
});
} else {
$(this).removeAttribute('attrId');
return true;
}
});
});
})(jQuery);
Your jQuery is... very wrong. $('href').attr('') is getting the empty attribute from an element <href>... Did you mean:
if( $(this).attr('href') == '')
A few things: event is undefined, as your event object is simply called e. Secondly, e.stopPropagation(); will not do what you want. stopPropagation simply prevents parent events from firing (eg: clicking a <td> will also fire click on the containing <tr> unless stopped).
Try just replacing your else statement with
return true;
Also your jQuery is incorrect (as stated in the other answer here).
This answer may help as well:
How to trigger an event after using event.preventDefault()
Good luck!
HTML:
<a href="#" class="button" onclick="sendDetails(\'Edu\')">
JS:
function sendDetails(type) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
names = $("#names" + type).val();
Input = encodeURIComponent($("#Input" + type).val());
....
The link jumps to top of page. I tried to use event.preventDefault() to stop jumping to top of page. However, it works only in Chrome and not in IE and Firefox. How can I solve it?
instead of "#" you can use javascript:; so there is no jumping, make sure to return false to disable the link-behavior
link
You can't only use the window.event to control an event. Try standardizing it like:
function sendDetails(e, type) {
var evt = window.event || e;
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
// ...
}
And your HTML would have to be:
ASDF
One other non-jQuery solution is to just modify your HTML to be:
ASDF
in which case you wouldn't have to use anything dealing with event in your sendDetails function. The return false; will prevent the default behavior automatically. But note - if any exceptions occur in your sendDetails function, the return false; won't execute and will allow the default behavior. That's why I like using preventDefault - you can call it immediately in the function to immediately stop the behavior, then do what you need.
At the same time, if you're using jQuery, try binding the click event like this:
$(document).ready(function () {
$(".button").on("click", function (e) {
e.preventDefault();
// Your sendDetails code (without the "event" stuff)
// OR call sendDetails (and remove the "event" stuff in the sendDetails function)
});
});
in which case your HTML would be:
ASDF
Although it would be a lot easier to target the specific elements that this applies to, instead of using the .button selector I provided. I'm sure the "button" class applies to more than just these targeted <a>, but maybe I'm wrong :)
Using jQuery is nice in this situation because it already standardizes the event object in a way that you can just use that e variable I included in the click callback. I'm sure it does a little more than just window.event || e, so I'd prefer/suggest using jQuery for handling events.
You are already using jQuery, just do it the jQuery way. jQuery wraps the event object and provides a normalized event object so you can just use the standard preventDefault, you don't need to fork depending on what the browser supports.
<button class="senddetail" data-type="edu">Education</button>
<button class="senddetail" data-type="com">Commercial</button>
<!-- why not just use a button instead of styling a link to look
like a button? If it does need to be a link for some reason
just change this back to an anchor tag, but keep the data
attributes and change the class to "button senddetail" -->
<script>
function sendDetails(type) {
// Assuming names and input are not globals you need to declare
// them or they will become implicit globals which can cause
// all sorts of strange errors if other code uses them too
var names, input;
names = $("#names" + type).val();
// you should only use capitalized variables for
// Constructor functions, it's a convention in JS
input = encodeURIComponent($("#Input" + type).val());
//....
}
// just calling $ with a function inside of the invocation
// is the same as using $(document).ready
$(function () {
// instead of using onClick, use jQuery to attach the
// click event in a less intrusive way
$('.senddetail').on('click', function (event) {
// no matter what browser this runs in jQuery will
// provide us a standard .preventDefault to use
event.preventDefault();
// jQuery sets 'this' to the DOM element that the event fired on,
// wrapping it in another jQuery object will allow us to use the
// .data method to grab the HMLM5 data attribute
var type = $(this).data('type');
sendDetails(type);
});
});
</script>
I'm trying to stop the browser from following certain links, rather I want to unhide some Divs when they are clicked.
I'm having trouble just getting the links to not be followed though.
Here's what I have:
var titles = $('a.highlight');
jquery.each(titles, function(){
this.click(function(){
return false;
});
});
It seems like the click handler is not being assigned. What am I missing?
Try
this.click(function(e){ e.preventDefault(); }
Actually, it looks like you might need to use the jQuery constructor on this:
$(this).click(function(){ return false; }
You could also try using parameters on the each function instead of using this:
jQuery.each( titles, function(index, elem) { $(elem).click( function() { return false; } ) } );
Personally, I would just do titles.each( ... though. In that instance you can use this to bind the click handler. I am not sure off the top of my head what this binds to with jQuery.each
Or just calling click on titles:
titles.click( function() { return false; } )
That will bind click to every element in titles. You don't need to loop through them.
You can compress that jquery a bit:
$('a.highlight').click(function() { return false; });
You should also make sure that:
There are no other click handlers registered for those elements later on.
The code you have is attaching after the elements have loaded. If they're not completely loaded, they won't be found in the $('a.highlight') selector. The easiest way to do this is to put your code in a $(document).ready(function() { *** code here *** }); block.
Edit: As per other responses - the problem was that this represents a DOM object, while $(this) is a jquery object. To use the .click function to attach a handler, you need a jquery object.
In short, using this inside the each loop won't work with what you're trying to do. You'll need to get a jquery representation by using $(this) instead.