I try to display an image with <img src="" alt="music cover">
using <span></span>
to display the music covers of my web radio.
The link is dynamic, it’s why I want to use the span tag for getting the url link of the image’s shown during music playback.
I’ve tried this, but it doesn’t work:
<center> <p class="current-playlist"> <span></span> </p> </center>
Here is my code:
<!DOCTYPE html> <html> <center><p class="current-playlist"><img src="<span></span"></p></center> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> var nowPlayingTimeout; var nowPlaying; function loadNowPlaying() { $.ajax({ cache: false, dataType: "json", url: 'https://my_radio_website.com/api/nowplaying_static/radio.json', success: function(np) { // Do something with the Now Playing data. nowPlaying = np; $('.current-playlist span').text(np.now_playing.song.art); nowPlayingTimeout = setTimeout(loadNowPlaying, 15000); } }).fail(function() { nowPlayingTimeout = setTimeout(loadNowPlaying, 30000); }); } $(function() { loadNowPlaying(); }); </script> </html>
Without the img tag, only the image link is shown, how could I proceed?
Advertisement
Answer
<img src="<span></span">
is not a valid HTML, you can not put another element into src
tag, you should only set image link to src
instead.
To do that, you can crate an <img src="">
element with an empty src
attribute.
Then, when you need to load the image you can put the image link into src
attribute.
Example:
const imageLink = "https://picsum.photos/200/300"; // setTimout to simulate ajax request setTimeout(() => { $(".current-playlist img").attr("src", imageLink); // OR document.querySelector('.current-playlist img').src = imageLink; }, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p class="current-playlist"> <img src=""> </p>