1

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?

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
Nate Pet
  • 44,246
  • 124
  • 269
  • 414

3 Answers3

3

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>');
});
j08691
  • 204,283
  • 31
  • 260
  • 272
2

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.

Community
  • 1
  • 1
Precastic
  • 3,742
  • 1
  • 24
  • 29
0

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>');
});
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111