I'm observing a behavior where onClick events cause a page to reload.
$('#target').click(function(){
$('#target').hide();
})
So the object is shown, it hides on click, but then page reloads and the object is shown again. I'm working on a website that was setup before me, so I'm not entirely aware of all its parts. Any idea what might cause this behavior and how to fix it?
I'm observing a behavior where onClick events cause a page to reload.
$('#target').click(function(){
$('#target').hide();
})
So the object is shown, it hides on click, but then page reloads and the object is shown again. I'm working on a website that was setup before me, so I'm not entirely aware of all its parts. Any idea what might cause this behavior and how to fix it?
Share Improve this question edited Apr 8, 2013 at 21:20 Evan Davis 36.7k7 gold badges52 silver badges58 bronze badges asked Apr 8, 2013 at 21:13 skyisredskyisred 7,1156 gold badges41 silver badges56 bronze badges 1-
How is this marked with a
php
tag? – AlbertEngelB Commented Apr 8, 2013 at 21:15
2 Answers
Reset to default 7You need to prevent the default event behavior with event.preventDefault
:
$("#target").on("click", function (e) {
$(this).hide();
e.preventDefault();
});
Using return false
will also work, but it does more than you may intend.
This is in line with the event cancellation standard
add a
return false;
as last statement so that the link is not called, only you function (onclick) is executed.