B Johnson B Johnson - 2 months ago 8x
HTML Question

event.preventdefault() issues - Trying to stop an anchor tag from loading

I'm setting up a dynamic and responsive video gallery, where you click on a thumbnail and it loads the accompanying video in the larger

above it. The problem I'm running into is that the event.preventdefault() apparently isn't working, because it still links to youtube rather than loading it. Any help is appreciated.


<div class="mainvideo">
<iframe src="https://www.youtube.com/watch?v=UAQ9-sl13zg" frameborder="0" allowfullscreen></iframe>
<div id="mainvideowords">

<div id="videogallery">

<div class="littlevideo">
<a href="https://www.youtube.com/embed/HsuzKk6udK8" class="video1"><img src="assets/placeholder.png"></a>
<div class="littlevideowords">


$(".video1, .video2, .video3").on("click", function(event) {
$(".mainvideo iframe").prop("src", $(event.currentTarget).attr("src"));


While not an answer as to why the event.preventDefault() isn't working, here's how I would approach this. I would adjust the html to look like this:

<div class="mainvideo">
   <iframe id="playVideo" src="https://www.youtube.com/watch?v=UAQ9-sl13zg" frameborder="0" allowfullscreen ></iframe>
 // notice ^^^^^^^^^^^^^^
        <div id="mainvideowords">
       // rest of your code

<div id="videogallery">
    <div class="littlevideo">
        <div data-link="https://www.youtube.com/embed/HsuzKk6udK8" class="video1">
       // notice ^^^^^   
    <img src="assets/placeholder.png"></div>

Then your jquery would look like this:

        var src = $(this).data('link');
        $('#playVideo').prop('src', link);

The selector at the beginning selects any div whose class begins with 'video', so you don't have to repeat video1, video2, etc. Then, we've added a custom html5 data attribute to our clicked div that we access with the .data('src') line. See docs here: http://api.jquery.com/data/ and https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes.

Finally, by adding an id to our iframe we can select it directly and change the src of the video.

Here's a fiddle for you: http://jsfiddle.net/1sLdkyr2/1/