jQuery Adds Extra '#' to URL? - javascript

I noticed sometimes that when I use jQuery, a extra '#' gets added to the end of my URL after a jQuery function is called. For example, the URL 'www.mywebsite.com' will change to 'www.mywebsite.com/#' once a jQuery function is initialized. The same for 'www.testsite.com/users.php', is changed to 'www.testsite.com/users.php#'.
Why does jQuery add the '#'?

If your function is running from a link onclick, you need to use event.preventDefault()
See http://api.jquery.com/event.preventDefault/

Probably you're getting this when handling a click event. If you don't want that happens, just add event.preventDefault() or return false at the end in event handler function.

Usually this is because you have a dummy link with a jQuery click handler. It's common to see links with an href of # that are only used to trigger some JavaScript.
Go
Resolve this easily by making a habit of calling e.preventDefault() in your click handlers:
$(function() {
$(".button").click(function(e) {
e.preventDefault();
...
});
});
You can also use return false, but that has the added effect of stopping event propagation. I like to add e.stopPropagation() explicitly if I also want that effect. It makes the code and it's intended effect more explicit and clear for future developers (or myself in 6 months).

Related

jQuery click on anchor tag reloads page

As many other threads and external forums suggest, I've tried placing e.preventDefault() (while passing e as parameter, not in code sample) in every place imaginable, but it doesn't prevent the anchor from reloading the page. When I step through the debugger, it will assign every div with scrollNav the click event, but when I click on the div-link it just reloads the page and the debugger does not stop on any lines in the highlightSelection function. Another method I've tried is to use an anonymous function inside this.click and place e.preventDefault() as the first line, but it does nothing.
I also don't really understand why you would want to place e.preventDefault() as so many others have suggested. Isn't it basically saying return false? That may stop a link from reloading the page, but won't it prevent the code in the method from executing?
jQuery(document).ready(function() {
jQuery('.scrollNav').each(initSideNavForSelection);
}); // end ready
function initSideNavForSelection() {
this.click(highlightSelection);
}
function highlightSelection() {
var selectedDataID = this.attr("data-id");
jQuery('.scrollNav').each(function() {
if (this.attr("data-id") === selectedDataID) {
this.addClass("selected");
} else {
this.removeClass("selected");
}
})
}
Add onclick="return false;" to the anchor.
OR change initSideNavForSelection function to
this.click(function(e) {
e.preventDefaults();
highlightSelection();
});
either works
There are a few things I had to do to get your codes to run. You can take a link at this fiddle here.
Here's the list:
Add JQuery as the framework to be used for your fiddle, under the Frameworks & Extensions section on the top left corner.
Remove the broken onclick="Event.stop(event)" inlined attribute as Event is undefined.
Replace the usage of this with $(this) in both your initSideNavForSelection() and highlightSelection() functions. this represents a DOM object and $(this) is a JQuery wrapper around this. The latter will respond to JQuery methods like .click(), but not the former.
So far, there is no page reload in your fiddle, with or without e.preventDefault().
Finally, in addition to event.preventDefault(), return false also calls event.stopProgagation() to prevent the event from bubbling up the DOM, before terminating the callback execution immediately. A call to event.preventDefault() doesn't terminate the function call immediately.

javascript object object on a href="javascript:..." call

I do have a simple script which is not working properly or as expected.
<script>
function modify_val(target, valeur)
{
$(target).val(valeur)
}
</script>
$row->movie2 ($row->counter relations)
The javascript is working properly as the targeted input value is modified but the page is "redirected" after the click with a page containing:
[object Object]
Why is there a print ? I don't understand... The OnClick method behave the same. href or OnClick="javascript:$('#type1').val('$row->movie2');" also behave the same.
Do you have any idea ?
PS : the page is in https mode.
The return value of an event handler determines whether or not the default browser behaviour should take place as well.
<script>
function modify_val(target, valeur)
{
$(target).val(valeur);
return false;
}
</script>
Change your HTML as. I would suggest you to use onClick attribute
$row->movie2 ($row->counter relations)
Demo
<a href=\"javascript:$('#type1').val('$row->movie2'); void(0);\">
works... Guessing as Mate suggested that a return is mandatory
You probably need to stop the default action of the link by passing the event object and calling preventDefault() or simply returning false from your inline event handler.
function modify_val(target, valeur) {
$(target).val(valeur)
return false;
}
See this post for info on returning false from an inline event handler: What's the effect of adding 'return false' to a click event listener?.
For the cleanest code, I'd recommend not using an inline event handler at all and simply use jQuery (which you seem to already have available) to install a click event handler and keep your code and HTML much more separate (generally considered a good practice). jQuery also allows you to return false from the event handler to prevent the default behavior.
See this article on Unobtrusive Javascript for more info on keeping your HTML and Javascript separate.

preventdefault not preventing when its inside button

I could not make preventdefault to prevent action. I apologize if the answer is too easy but I simply cant find the error. why is it not preventing from entering the link? jsfiddle given below.
http://jsfiddle.net/zwY5p/34/
$('#theForm').click(function(e) {
event.preventDefault();
alert('FORM!');
});
e != event
$('#theForm').click(function(event) {
event.preventDefault();
alert('FORM!');
});
The parameter passed to the handler function is what you need to execute preventDefault on. In your code, you are passing e but calling preventDefault on event.
preventDefault prevents the default browser action. It does not cancel the inline JavaScript, since that runs first. If you have to override that, just remove it (no event listener necessary):
$('#theForm').removeAttr('onclick').
your event parameter name e and the variable you are using event are different,
$('#theForm').click(function(event) {
event.preventDefault();
alert('FORM!');
});
Other than the errors pointed out on other answers there's another small issue, specifically in your markup declaration:
<!-- Use either the closing tag or the slash (/) in the opening tag -->
<button id="theForm" onclick="location.href='http://www.example.com'" />
go to google
</button>
On the topic, you have two different handlers attached to the button element, they are both handling the click event but they are still different and separate things. jQuery won't know about the handler defined in the markup:
var btn = document.getElementById('theForm');
jQuery._data( btn, "events" );
will return an array with a single element which is the handler added via jQuery.
Now you have to re-evaluate the need of two different handlers for the same element and event and apply conditions. Do you really need to do it this way?
You're using 2 'click' events.
You end up using preventDefault once, and it's used after the 1st click event has ran.
If you make your button an href, then your preventDefault will be working.
It will also make more sense, as the JS will be separated from the HTML markup.
Also, of course you must use the same parameter name. (function(event), with event.preventDefault for example).
If you are passing "e" as an event to the function then you should prevent the default action only for that "e" that you have passed and not for "event".
$('#theForm').click(function(e) {
e.preventDefault();
alert('FORM!');
});
jQuery preventDefault() method: http://api.jquery.com/event.preventDefault/

jQuery - Add e.preventDefault() to all links click events?

I'm making a script in jQuery, and I have many click links click events. The thing is that I don't want the links I have click events for to do anything except the event, so I put an e.preventDefault(); at start of all my click events. But I have many click events, so is there a more simple way to just add the e.preventDefault(); to all the links click events? Remember I also have some links that I want to work as they should, so adding the e.preventDefault(); to all the links won't work, I only want to add it to links with click event.
you can use jquery namespaced events
http://docs.jquery.com/Namespaced_Events
HTH
you can do something like this for the links you want to add a click event but prevent the default behaviour
$('a.someClass').bind('click.dontClick',function(e){
e.preventDefault();
});
and for the links you want the normal click behaviour
$('a.clickClass').bind('click.doClick',function(e){
//your event handling code here
});
DEMO
You could try overriding the bind method, or the click method, before any of your binding code runs. Here I'm overriding the click method in a fairly hacky way. I would really recommend just calling preventDefault where you need it.
(function(){
var original = jQuery.fn.click;
jQuery.fn.click = function(){
// wrap your function in another function
var f = arguments[0];
arguments[0] = function(e) {
e.preventDefault();
f(e);
}
original.apply( this, arguments );
}
})();
Example in action: http://jsfiddle.net/k4jzb/
This SO answer details how to detect events on an element, but it looks like the asker took that answer and built a jQuery plugin for selecting elements based on their event listeners.
So you could use that plugin and then use some event delegation like so:
$(document).delegate('a:Event(click)', 'click', function (e) { e.preventDefault(); });
Warning: I've never used this plugin myself, and I'm not really familiar with custom jQuery CSS filters, so this might not actually work. At all.
I would take #3nigma's answer a little further. Usually the links you don't want to do default actions on are like <a href="#">
So filter out these links so the page doesn't jump when clicked. I use jQuerys filter() function. Not sure if that is the best. What do you think?
$('a').filter(function(i) {
return $(this).attr("href") === "#";
})
.bind('click.dontClick',function(e){
e.preventDefault();
})
Example here: Filter a tags containing #

jQuery's click() is not clicking?

I thought jQuery's click() can let us add a handler or just click on an element?
However, I tried:
$(function() {
setTimeout(function() {
$('a').first().trigger('click'); // or click(), the same
}, 3000);
});
and waited 3 seconds and it won't click on the first <a> element in the page... how come?
Update: this is related to What is the best way to make the Yahoo media player autostart, jQuery? and so there should already be event handler for clicking on a media, so how come .click(), which is the same as trigger('click'), not firing off that event handler?
Calling the click() method does not simulate clicking the link. It calls any click() handlers on the affected element(s). That's a subtle yet important difference. If you want to simulate clicking the link, there is no realiable cross-browser way of doing this.
I very recently ran into a similar problem. The reason nothing happens is because anchor tags don't have a "click" method for jquery to call. If you change the anchor tag to a <button></button> tag for instance, the .click() will simulate a user clicking as expected.
There are a few "hacky" workarounds for this, but it would depend how the event handler for the anchor tag is set up. For instance, if there was some javascript inside the anchor tags href attribute, this would work (which happened to be the solution to my problem):
var lnk = $('a.mylink');
window.location = lnk.attr('href');
I'm not sure, if .first() is a possible way to use this function. Have you tried
$('a:first').click();
instead? If .first() doesn't exist, it throws an error, the .click() is never reached, and since it lives in an anonymous function, you even might not see the error at all (failing silently).
Here's what you could do to simulate a click on a link (as long as these are normal links):
location.href = $('a').first().get(0).href;
If you already have an event-handler for the link, you can use the trigger() method:
$('a:first').trigger('click');
What exactly do you want to do? A link is usually used to redirect to a new page. So if you need a redirection, use something like this:
$(function() {
setTimeout(function() {
window.location.replace("linkToNewPage.html");
}, 3000);
});
"There is an option for this. Plz check
at this page
http://mediaplayer.yahoo.com/api/#example_usage
If u set autoplay=true, the first song
will be started automatically.."
-Kai
In Relation to:
What is the best way to make the Yahoo media player autostart, jQuery?
Else for a click attach a click handler to what you want e.g:
$('#MyElementID').click(function() {
//How you want it to behave when you click it.
});
window.setTimeout(YourFunction, 3000);
function YourFunction {
//Your function that runs. Maybe fire the onclick handler?
}
?
You're trying to use click() method for something else than its purpose. click() is used so you can catch the click on a specific element, not for simulate it.
Read more here

Categories

Resources