Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript change img src attribute without jQuery

How to change the src attribute of a HTMLImageElement in JavaScript?

I need help to convert logo.attr('src','img/rm2.png') to vanilla JavaScript.

window.onresize = window.onload = function () {
    if (window.innerWidth > 1536) {
        var logo = document.getElementById('rm');
        logo.attr('src','img/rm2.png');
    }
};
like image 447
technopeasant Avatar asked Mar 16 '12 04:03

technopeasant


People also ask

How to set src attribute in js?

You can change an HTML image src attribute programatically by using JavaScript. First, you need to grab the HTML element by using JavaScript element selector methods like getElementById() or querySelector() and assign the element to a variable.

What is IMG src in JavaScript?

Definition and UsageThe required src attribute specifies the URL of an image. Note: The src property can be changed at any time. However, the new image inherits the height and width attributes of the original image, if not new height and width properties are specified.

What is IMG src in HTML?

The <img> tag is used to embed an image in an HTML page. Images are not technically inserted into a web page; images are linked to web pages. The <img> tag creates a holding space for the referenced image. The <img> tag has two required attributes: src - Specifies the path to the image.


2 Answers

You mean you want to use pure javascript?

This should do it:

var logo = document.getElementById('rm');
logo.src = "img/rm2.png";

So your function should look like :

window.onresize = window.onload = function () {
    if (window.innerWidth > 1536) {
      var logo = document.getElementById('rm');
      logo.src = "img/rm2.png";
    }
};

Note: You could also use element.setAttribute. BUT, see this post for more:
When to use setAttribute vs .attribute= in JavaScript?

like image 112
gideon Avatar answered Oct 26 '22 07:10

gideon


try this...hope it works

window.onresize = window.onload = function () {
    if (window.innerWidth > 1536) {
        var logo = document.getElementById('rm');
        logo.setAttribute('src','img/rm2.png');
    }
};
like image 26
Tejasva Dhyani Avatar answered Oct 26 '22 06:10

Tejasva Dhyani