I\'ve got a page with some questions and answers, the answers are collapsed by default. When they click the question I expand the hidden answer-div. The problem is that when
You are looking for event.preventDefault
(see jQuery API).
$(...).click(function(e) {
e.preventDefault();
// your code
});
You need to add preventDefault()
to your click handler. This will stop the browser executing it's own link handler, and will only run the code you specify.
Example:
$("#myID").click(function(e) {
e.preventDefault();
// Do your stuff
});
If you add a "\" to the "#" it will prevent from going to the top.
<a href="#\" id="myID">Myquestion</a>
HTML:
<a id="like-post" href="#\">like</a>
JavaScript:
$('body').delegate('#like-post','click',function(e) {
e.preventDefault();
.....
});
$('body').on('click', '[href^=#]', function (e) {
e.preventDefault()
});
if the selector ex.."body" is there during the initial render then use the any selector .. id ... to target the general to have jQuery (as of 1.8.2) iterate over. the "On handler invoke a method called "bind" which is used for newly added content to the DOM",. Using the "[href^=#] will select any href that are in the section tag but you can replace section with anything or nothing and it applies a cancellation to the click event. This technique is great for dynamically created content to the DOM
Inside your function of:
And I've used jQuery and .click as event-listener.
Will look something like:
$("#myID").click(function(){});
Change this to (don't forget the param e inside function(e)
:
$("#myID").click(function(e){
e.preventDefault();
});