2

I need to change iframe src on click. Due to some reason I wish to use event.target and not any other method.

I am trying to achieve the same using the below code but it is not working.

html code:

<div id="div2" class="sim-row-edit-video">
<iframe class="frame" width="auto" src="https://www.youtube.com/embed/tgbNymZ7vqY"></iframe>
</div>

I would rather not use class or id to change the same as there are many with similar class. Kindly use event.target.

js code:

$(".sim-row-edit-video").click(function(){
    alert("video clicked");
    $(event.target).attr('src', 'https://www.youtube.com/embed/drOnSwo1Ob0');

//event.target.src = 'https://cdn.iconscout.com/icon/free/png-256/car-location-find-navigate-gps-location-29571.png';
});

How can I change the src of the clicked iframe?

2
  • You can't detect clicks on a cross-domain iframe document. Commented Sep 13, 2018 at 8:04
  • i can detect the click on parent div, any solution using that please Commented Sep 13, 2018 at 8:05

1 Answer 1

4

you can use $(this).find('iframe'). Here $(this) is the object of clicked element and find('iframe') will find the iframe element inside the clicked element. Following snippet is an example based on code you have provided.

$(".sim-row-edit-video").click(function(){
    console.log("video clicked");
    console.log("old src: " + $(this).find('iframe').attr('src'));
    $(this).find('iframe').attr('src', 'https://www.youtube.com/embed/drOnSwo1Ob0');
    console.log("new src: " + $(this).find('iframe').attr('src'));
//event.target.src = 'https://cdn.iconscout.com/icon/free/png-256/car-location-find-navigate-gps-location-29571.png';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div2" class="sim-row-edit-video">
<iframe class="frame" width="auto" src="https://www.youtube.com/embed/tgbNymZ7vqY"></iframe>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.