I have the iframe receiving it's src from the input for each instance of the .item but I think my code is iterating over every instance of .item whenever a keyup happens.
How do I modify the code to only execute on the .item for which the input of that item is being changed? I want to have it where the iframe appears after the url has been copy / pasted. It doesn't have to be on keyup but whenever the url is successfully entered -> show the iframe.
Bonus requirement :: I only want to show the iframe if it has a value entered in it's associated input, either on load or when the link has been entered.
Codepen: https://codepen.io/moofawsaw/pen/wvGNvrx
$(document).ready(function() {
iframeKeyup();
function getId(url) {
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[2].length == 11) {
return match[2];
} else {
return "error";
}
}
$("input").on("keyup change", function() {
iframeKeyup();
});
var myId;
function iframeKeyup() {
$(".item").each(function() {
var $this = $(this);
var myUrl = $this.find("input").val();
myId = getId(myUrl);
$this
.find(".iframe")
.html(
'<iframe width="100%" height="100" src="//www.youtube.com/embed/' +
myId +
'" frameborder="0" allowfullscreen></iframe>'
);
});
}
});
.item {
height: 100px;
width: 100px;
margin: 1.3rem
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
<input type="text" value="https://www.youtube.com/watch?v=I7QJkecUpi8" />
<div class="iframe"></div>
</div>
<div class="item">
<input type="text" value="" />
<div class="iframe"></div>
</div>