kevingilbert100
kevingilbert100

Reputation: 1333

JavaScript "<SCRIPT>" in Image src attribute

So I have the following JavaScript function.

var LogoUrl = function() {
    document.write('views/img/common/site-logo.svg');
}

And I want to have this function used in a html img src attribute.

Here is a example though this syntax wouldn't work, it should give you an idea of what I am looking for.

<img class="site-logo" src="<script> LogoUrl() </script>" alt="Site Logo">

And hoping this would export the following in the browser

<img class="site-logo" src="views/img/common/site-logo.svg" alt="Site Logo">

What is the best approach to doing this?

Upvotes: 0

Views: 3341

Answers (3)

andyw_
andyw_

Reputation: 500

You could do this - but this makes it obstructive.

<script>document.write("<img class=\"site-logo\" src=\"views/img/common/site-logo.svg\" alt=\"Site Logo\">")</script>

It is also not very organised because it ties everything so much with the markup that you might as well just have it as markup.

You're better off doing it properly by changing the src property

var logo = document.getElementsByClassName('site-logo')[0];
logo.src = 'http://www.develop.com/Images/v3/tech-symbols/angularjs_logo.png';

demo here http://jsfiddle.net/andyw_/XxTuA/268/

If this is all you need to do - I don't think it justifies the use of a selector library or front-end framework.

Upvotes: 0

Joeytje50
Joeytje50

Reputation: 19112

You can do this with the following instead:

<script>
    document.write('<img class="site-logo" src="' + 'views/img/common/site-logo.svg' + '" alt="Site Logo">');
</script>

Since the script tag is indeed a tag, you can't put it inside the attributes of another tag.


A much better approach however would be the following:

Prepare a span element for the element to appear in, and give it a specific id. This would be your HTML:

This is my image: <span id="myImg"></span>.

and this will be your jQuery code:

$(function() {
    $('<img>').class('site-logo')
        .attr('src', 'views/img/common/site-logo.svg')
        .attr('alt', 'Site Logo')
        .appendTo('#myImg');
});

Alternatively, instead of preparing a span, you could prepare the image without defining a src attribute, with the following HTML:

This is my image: <img id="myImg" class="site-logo" alt="Site Logo">.

and the following jQuery code:

$(function() {
    $('#myImg').attr('src', 'views/img/common/site-logo.svg');
});

Upvotes: 2

Kamrul
Kamrul

Reputation: 7301

You can use jquery $(document).ready() to set the image src.

$(document).ready(function (){
        $('img.site-logo').attr('src', 'views/img/common/site-logo.svg');
      });

Upvotes: 1

Related Questions