Skip to content Skip to sidebar Skip to footer

How To Swap Image And Video To Another Div?

I am trying to swap image and the videos when user clicks a selected element I have something like the following:

Title

Solution 1:

Take those classes out of the elements and create another wrapper div. You can assign it to .main as well, but I'm not too sure what you're doing with .main, so I'll just leave that alone.

<divclass='container'><h1class='title'>Title</h1><divclass='row'><divclass='main'><divclass='col-md-7 col-sm-8 img-responsive'><imgclass='img-responsive'src='main.png'/></div></div></div><divclass='row'><ahref='#'class='component'><divclass='col-md-4 col-sm-4'><videoclass='video'controls><sourcesrc='video1.mp4'/></video></div></a><ahref='#'class='component'><divclass='col-md-4 col-sm-4'><videoclass='video'controls><sourcesrc='video2.mp4'/></video></div></a><ahref='#'class='component'><divclass='col-md-4 col-sm-4'><imgclass='img-responsive'src='img1.png'/></div></a></div></div>

and then you can do something like this to select and swap the media.

$('.component').on('click', function(){
   var mainSrc = $(this).closest('.container').find('.main:first-child').html();
   var newSrc  = $(this).children().first().html();
   $(this).html(mainSrc)
   $(this).closest('.container').find('.main:first-child').html(newSrc);
})

Solution 2:

Given your HTML, here is a jsfiddle of a solution.

$('.component').click(function () {
    var clickClass = $(this).children(0).attr("class");
    var mainClass = $(".main").children(0).attr("class");
    var clickHTML = $(this).html();
    var mainHTML = $(".main").html();
    $(this).html(mainHTML);
    $(".main").html(clickHTML);
    $(this).children(0).attr("class",clickClass);
    $(".main").children(0).attr("class",mainClass);
});

I have added Bootstrap but don't have the image files.

Post a Comment for "How To Swap Image And Video To Another Div?"