Reputation: 73
I want to replace the gif file by javascript. I find the method below. Is there any way i can place the javascript tag before the img tag?
<img class="myImg" src="compman.gif" width="107" height="98">
<script>
document.getElementsByClassName("myImg")[0].src = "hackanm.gif";
</script>
Upvotes: 2
Views: 36888
Reputation: 99
<div class="album_pic">
<img src="/Images/logo.jpg" id="track_art" alt="cover image" /> </div>
let DIV = document.createElement('div');
DIV.classList.add('album_pic');
DIV.innerHTML = `<img src="${PlayList[songIndex].album_pic}" class="track_art" alt="cover image">`;
let Cover_image = document.querySelector('.album_pic');
Cover_image.replaceWith(DIV);
In place of "PlayList[songIndex].album_pic" , add your own path. This is my research and I don't copied from anyone. Also this is all based on what I learned in javascript
Upvotes: 0
Reputation: 5
I believe OP's main concern was flash of the old image before it is replaced by JavaScript. I suggest you add a line of CSS to make your image element visibly hidden then do the swap + unhide with JavaScript.
<style>
.myImg {visibility: hidden;}
</style>
<img class="myImg" src="compman.gif" width="107" height="98">
<script>
var imgReplace = document.getElementsByClassName("myImg")[0];
imgReplace.src = "hackanm.gif";
imgReplace.style.visibility = "visible";
</script>
Upvotes: 0
Reputation: 3883
A page can't be manipulated safely until the document is "ready." Using jquery's $(document).ready()
, it Will wait until the page is loaded and ready to be manipulated before executing (no matter where it is on the page). Example:
<script>
$(document).ready(function() {
document.getElementsByClassName("myImg")[0].src = "hackanm.gif";
});
</script>
<img class="myImg" src="compman.gif" width="107" height="98">
You could also then leverage selectors inside jquery (e.g. $(".class")
where class is your class, or $("#id")
where id is the id) and change the code to:
<script>
$(document).ready(function() {
$(".myImg").attr('src',"hackanm.gif");
});
</script>
<img class="myImg" src="compman.gif" width="107" height="98">
And further you could even store it in a variable if you wanted to change it later on in javascript as well!
<script>
$(document).ready(function() {
var myImg = $(".myImg");
var newImg = "hackanm.gif";
myImg.attr('src', newImg);
});
</script>
<img class="myImg" src="compman.gif" width="107" height="98">
Hope this helps you learn a few new tricks inside javascript! Happy coding!
Upvotes: 3