I have a gallery of photos with a next and previous button. If one of my javascript methods is broken for one reason or another when one of the buttons is clicked it will add a hash to the url i.e. www.google.com# . I know the hash can be given a div id to jump to that part of the page but when it's blank it jumps around my page a few times and I'm not sure what it's targeting. I thought of attempting to remove the hash from the url but then I'd have to ensure that on every action and that seems like bad practice. I would prefer if the hash just made no difference to the actions on the page.
Don't use href="#", it is improper.
Instead, use href="javascript:;" or a variant thereof (personally I use javascript:void(null);)
This explicitly states that the link does not go to another location, but is handled by JavaScript.
I guess Next And Prev button has <a href="#" ...</a> like markup. In this case you can add event listener to those links with jquery
$('#prev, #next').on({
'click': function(e) {
e.preventDefault();
}
})
and avoid changing location by browser. Or in pure javascript:
document.querySelectorAll('#prev, #next').addEventListener('click', function(e) {
e.preventDefault();
},false)
//Note: this code is not cross-browser
Don't use an anchor tag when you don't want to perform a navigation function. Use button
Related
How to make js cut off and change jump links?
Not just changing the herf of <a>.
There is no way to stop the jump of js.
I want to make a php proxy like https://github.com/joshdick/miniProxy but it's not perfect.
When encountering a jump with js, it will not work.
You can preventDefault behaviour with JS. By default it will redirect to link but you can:
document.getElementById("yourlink").addEventListener("click", function(event){
event.preventDefault()
});
Also, you can access your link with:
document.getElementById("yourlink").href;
or event.target.href inside your listener
Your a tag will need to have id of yourlink to achieve that:
<a href="someurl" id="yourlink" />
I have a general question about jQuery.
I have created few jQuery buttons but the problem that I have is when you scroll half way down the page and you press the button, the page jumps back to top, instead of staying in the middle where the button is??
How can you stop this from happening, as it's frustrating for the user??
Is there any particular reason why it's happening?
jsFiddle Example:
$(".comment-here").click(function() {
$(".comment-form").slideToggle('slow');
});
$(".main-btn.orange").click(function(){
$(".comment-form").slideUp('slow');
});
You're not preventing the default event. Since you're clicking on an anchor tag, the default event for # is just to jump up to the top of the document.
To prevent this from occurring:
Pass the event into the function, and use preventDefault();
$(".comment-here").click(function(e){
e.preventDefault();
$(".comment-form").slideToggle('slow');
})
$(".main-btn.orange").click(function(e){
e.preventDefault();
$(".comment-form").slideUp('slow');
})
You could also use return false; instead, which goes a bit further than just preventing the default event, it will stop events bubbling up to parent elements.
Add return false; to the click handler of the <a class="comment-here">.
Essentially it is not jQuery, but the default browser behaviour that causes this: you clicked a link, it has to navigate to its href, which is... "#", i.e. this page. So there we go back to this page (the top).
Prevent default behaviour of anchor tags:
$(".comment-here").click(function(e){
e.preventDefault();
//....
});
The problem is with your <a> tag using href="#" which references the current page and pulls you to the top.
I'd recommend the following approaches, instead of the default event prevention mentioned in other answers. Of course those work, but why use an element only to remove it's default functions?
Ergo, use something that is intended for your purpose:
1.) Use a <button> instead of <a>:
http://jsfiddle.net/RvHjx/7/
2.) If you're dead set on using <a>, remove the href attribute in your <a> tag. This will remove the blue-underlined link styling (the link still functions correctly though), but it's easy to fix with some CSS:
http://jsfiddle.net/RvHjx/11/
Adding javascript:; to your a tags href is the simplest way.
my link
I have a tag like below. The question I have is how do I make this <a/> tag not behave like a link when user right clicks it. Since on a regular click the onclick event will fire and return false I am good with the regular click on the link the issue comes when a user right clicks the mouse and then gets the option like open in new tab or open in new window I have to prevent this from happening. I found out I can use javascript:void(0) in the href to do that but for some reason I cannot change the href as it is used for some other stuff. Is there any even or something that I can use.
<A title="Test1" onclick="javascript:search1('search'); return false;"href="team">search</A>
Thanks
as often, there's no universal solution, every browser do it its way. HTML 5 says form.oncontextmenu event handler should be supported. So this
<script>
document.oncontextmenu=function("alert('dont play with sources');return false");
</script>
should work if you use HTML 5.
you can also remove the javascript word, onclick already waits for js code (as oncontextmenu does).
<a onclick="search1('....
I have jQuery that I have written that is supposed to find a particular <a> tag and change its behavior. Before jQuery loads, the <a> tag has an href attribute that points to another page. I am using jQuery to change the behavior of the <a> tag so that rather than directing the browser to load that other page, it instead runs javascript when clicked that loads content dynamically in a <div> that is positioned at the location of the mouse pointer.
So, for example, I have the following:
<a class="funk" href="http://example.com/page2.html">Link</a>
<div class="hidden bubble">Load this instead.</div>
The jQuery I have running does the following:
$(document).ready(function(){
$('.bubble').hide()
$('.bubble').removeClass('hidden');
$('.funk').attr('href', '#');
$('.funk').click(function(e){
$('.bubble').show();
})
})
The problem I have is: Whenever the user clicks the link, the browser acts on the href="#" attribute and brings scrolls the browser to the top of the page. What is the most "correct" way to make my site so that the browser does not scroll at all, but instead merely executes the jQuery code that I have written for the click event?
Let the 'click' function return false. That cancels the event, and the browser doesn't follow the link. In this case, you can even let the href attribute at its original value.
$('.funk').click(function(e){
$('.bubble').show();
return false;
//--^
})
To be on the save side, you can explicitly cancel the event:
e.preventDefault(); // no default action
e.stopPropagation(); // event doesn't bubble up or down in the DOM
Add this to your click function:
$('.funk').click(function(e){
e.preventDefault();
e.stopPropagation();
$('.bubble').show();
});
This will do what is implied by the method names.
Call e.preventDefault() in the click handler.
http://api.jquery.com/event.preventDefault/
When I want some link to not do anything but only respond to javascript actions what's the best way to avoid the link scrolling to the top edge of the page ?
I know several ways of doing it, they all seem to work fine :
Hello
or
<a id="hello" href="#">Hello</a>
<script type="text/javascript>
$(document).ready(function() {
$("#toto").click(function(){
//...
return false;
});
});
</script>
and even :
<a id="hello" href="#">Hello</a>
<script type="text/javascript>
$(document).ready(function() {
$("#toto").click(function(event){
event.preventDefault();
//...
});
});
</script>
Do you have any preference ? why ? in which conditions ?
PS: of course the above examples assume you're using jquery but there's equivalents for mootools or prototype.
Binding:
javascript: URLs are a horror to be avoided at all times;
inline event handler attributes aren't brilliant either, but OK for a bit of rapid development/testing;
binding from script, leaving the markup clean, is typically considered a best practice. jQuery encourages this, but there is no reason you can't do it in any library or plain JS.
Responses:
In jQuery return false means both preventDefault and stopPropagation, so the meaning is different if you care about parent elements receiving the event notification;
jQuery is hiding it here but preventDefault/stopPropagation have to be spelled differently in IE usually (returnValue/cancelBubble).
However:
You have a link that isn't a link. It doesn't link anywhere; it's an action. <a> isn't really the ideal markup for this. It'll go wrong if someone tries to middle-click it, or add it to bookmarks, or any of the other affordances a link has.
For cases where it really does point to something, like when it opens/closes another element on the page, set the link to point to #thatelementsid and use unobtrusive scripting to grab the element ID from the link name. You can also sniff the location.hash on document load to open that element, so the link becomes useful in other contexts.
Otherwise, for something that is purely an action, it would be best to mark it up like one: <input type="button"> or <button type="button">. You can style it with CSS to look like a link instead of a button if want.
However there are some aspects of the button styling you can't quite get rid of in IE and Firefox. It's usually not significant, but if you really need absolute visual control a compromise is to use a <span> instead. You can add a tabindex property to make it keyboard-accessible in most browsers although this isn't really properly standardised. You can also detect keypresses like Space or Enter on it to activate. This is kind of unsatisfactory, but still quite popular (SO, for one, does it like this).
Another possibility is <input type="image">. This has the accessibility advantages of the button with full visual control, but only for pure image buttons.
The only advantage that I can think of to using javascript:void(0) is that it will be supported even by the oldest browsers. That said, I would use one of the other unobtrusive approaches you have mentioned:
For most uses, event.preventDefault() and return false can be used interchangeably.
event.preventDefault() will prevent the page from reloading, as desired, but will allow the click event to bubble up to the parent. If you want to stop the bubbling, you can use it in conjunction with event.stopPropagation.
return false will additionally stop the event from bubbling up to the parent.
I say 'interchangeably' in the first point above because much of the time we do not care whether or not an event bubbles up to the parent(s). However, when do we need some fine-tuning, we should consider points two and three.
Consider the following example:
<div>Here is some text Click!</div>
$("a").click(function(e) {
e.preventDefault();
});
$("div").click(function() {
$(this).css("border", "1px solid red");
});
Clicking on the anchor will prevent the default action of the event from being triggered, so the browser will not redirect to www.google.com. However, the event will still 'bubble up' and cause the div's click event to fire, which will add a border around it. Add e.stopPropagation() or just return false and the div's click event will not fire. You can mess with it here: http://jsfiddle.net/cMKsN/1/
Dreamweaver uses a nice little trick by default that I've started using.
<a href='javascript:;'></a>
It's small, it doesn't trip and anchors and it's library agnostic.
I tend to prefer using return false, as that gives the option to give the user a choice whether to continue that action, such as shown here, in quirksmode:
http://www.quirksmode.org/js/events_early.html#default
It's simple, it's old, but it works well, cross-browser, regardless of the version of javascript.
event.preventDefault() and return false; are one thing - they instruct the browser not to process the default action for the event (in this case, navigating to the href of the anchor tag that was clicked). href=javascript: and its ilk are something else - they're causing the default action to be 'do nothing'.
It's a question of style. Do you want to do all your work in the onclick, or do you want to be able to put actions in both the onclick and the href and rely on the capabilities of the browser to modulate between the two?
I like using href="javascript:void(0)" in the link as # implies jumping to the top of the page and that may in fact happen if for some reason your jQuery event does not load e.g. jQuery fails to load.
I also use event.preventDefault(); as it will not follow the link even if an error is encountered before return false; for example:
HTML:
<a id="link" href="http://www.google.com">Test</a>
jQuery Example 1:
$("#link").click(
function(){
alert("Hi");
invalidCode();
return false;
}
);
jQuery Example 2:
$("#link").click(
function(event){
event.preventDefault();
alert("Hi");
invalidCode();
return false;
}
);
Since invalidCode(); will throw an error return false is never reached and if jQuery Example 1 is used the user will be redirected to Google whereas in jQuery Example 2 he will not.
I think that I have seen as well javascript:; around as the web develops, is hard to keep track to the tricks that are available out there.. but this is mainly about accessability (besides javascript:void(0); ) and just a small correction is not javascript:void(0) but javascript:void(0); which means do nothing so pretty much as return false; although not sure if javascript:return false; does the same..
I always use and would suggest to use javascript:void(0); for a couple of reasons.. in my humble opinion, of course.
1.) I use it because of the same someone mentioned above.. href="#" is not appropriate as it might indicate going to the top and even in that case '#top' would be more adequate for that case. But also this can trigger something else in your code that makes use of # (hashes) so another reason is to avoid conflicts with other javascript that might be using #. And I tend to look for this when using a plugin for example, and replace them immediately.. href='#' to href='javascript:void(0);' or href='javascript:;'
2.) If I want to re-use a function for a group of specific Anchor tags, I can call it with the selector on any attribute without worrying about detecting the click event and preventing the default action and I do it without even thinking of it as a development preference.
3.) In most cases if you are doing link building using javascript:void(0); tries to make a link to not be followed as the old href= rel=nofollow so it avoid indexing links that are actions. I'm not so sure about this one merely because I heard that crawlers and robots can now read even Flash so would not be surprised if they can read javascript links
4.) Referring from 2.) you can target on a class like and forget about preventing the click event default action by using a href="javascript:void(0);" and then targetting the class directly from the selector at the jQuery function.
jQuery(function($)
{
//from the rel
$('a[rel="-your-rel-id"]') ... off('click').on('click',function()
//from the class
$('a.-the-class') ... off('click').on('click',function()
//from the id
$('a#-the-id').off('click').on('click',function()
{
--do something with this link
});
});
I rather feel more comfortable using the class as you can always do...
$(a#-your-id).hasClass(-yourclass-)
or any other interesting combination and affect many links.. so I really won't suggest to use the A as a selector solely..
Normally what I see in here being suggested is this:
jQuery(function($)
{
//from the rel
$('a[rel="-your-rel-id"]').on('click',function(event)
//do something
//prevent the click as is passed to the function as an event
event.preventDefault();
});
});
I'd rather not put JavaScript into the href because that's not what it's meant for. I prefer something like
Link