Nate Pet
Nate Pet

Reputation: 46222

jquery click prevent going to top of page

I have a number of images on my page. Some are at the bottom of the page which requires scrolling. What I am finding is that when I click on the image which in turn turns into a video it makes me to go the top of the page.

Here is the code I have:

$('#videoconner').click(function () {
     $(this).replaceWith('<iframe width="280" height="164" src="http://www.youtube.com/embed/6kR2n4344UCAU?autoplay=1&cc_load_policy=1&rel=0" frameborder="0" allowfullscreen></iframe>');
});

I added :

e.preventDefault();

but that did not help.

Is there anyway to prevent from going to the top of the page?

Upvotes: 1

Views: 228

Answers (3)

Precastic
Precastic

Reputation: 4001

You want to return false; to make it stop the click event from doing the default action & continuing to bubble up the DOM:

$('#videoconner').click(function () {
  $(this).replaceWith('<iframe width="280" height="164" src="http://www.youtube.com/embed/6kR2n4344UCAU?autoplay=1&cc_load_policy=1&rel=0" frameborder="0" allowfullscreen></iframe>');
  return false;
});

Read this for more info on the subject: event.preventDefault() vs. return false

Note: Returning false only calls e.stopPropagation if using jQuery, as this question does.

Upvotes: 2

Adil Shaikh
Adil Shaikh

Reputation: 44740

You need to use preventDefault like this (add e in callback function parameter)

$('#videoconner').click(function (e) {
  e.preventDefault();
  $(this).replaceWith('<iframe width="280" height="164" src="http://www.youtube.com/embed/6kR2n4344UCAU?autoplay=1&cc_load_policy=1&rel=0" frameborder="0" allowfullscreen></iframe>');
});

Upvotes: 0

j08691
j08691

Reputation: 207861

Add an e (for the event parameter) to your click function.

$('#videoconner').click(function (e) {
    e.preventDefault();
    $(this).replaceWith('<iframe width="280" height="164" src="http://www.youtube.com/embed/6kR2n4344UCAU?autoplay=1&cc_load_policy=1&rel=0" frameborder="0" allowfullscreen></iframe>');
});

Upvotes: 3

Related Questions