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?

Mohammad Adil
  • 44,013
  • 17
  • 87
  • 109
Nate Pet
  • 41,226
  • 116
  • 259
  • 398

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
  • 197,815
  • 30
  • 248
  • 265
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,502
  • 1
  • 21
  • 28
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>');
});
Mohammad Adil
  • 44,013
  • 17
  • 87
  • 109