I want to assign the function below with a button, but by some reason the ‘location.href’ part in the function doen’t work. If I change from a button to a div it works, so the problem seems to be with the button.
How come it doesn’t work and is there a way of solving it (I really want to use a button)?
<button id="back">Cancel</button> // Doesn't work
<div id="back">Cancel</div> // Works
$('#back').click(function(){
var imageId = $('#id').attr('href');
var id = imageId.split('/');
location.href = '/blog/' + id[3];
});
Your problem is not the button, your problem is the fact that when you bind a click to an element with a default behavior, like a
linkorbutton, the browser executes the script but first starts following the default behavior.You either use
return false;to prevent the default behavior from triggering, and also prevent other actions associated with the element to bubble up:See this working Fiddle Example!
or you use
.preventDefault();to only prevent the default behavior but perform other actions associated with the element:See this working Fiddle Example!
There’s a good article on the subject here!