user1481850
user1481850

Reputation: 248

javascript - change image width?

I am using the following code to check if the width of an image is larger than 700. If that the case then I want to set it to 700

    <img src="" id="main_image">
<script>
    if(document.getElementById(main_image).width > 700) {
    document.getElementById(main_image).width = 700;
    }
    </script>

after some search I found the above code but it is not working. Tell me what I am doing wrong ?

Upvotes: 0

Views: 4811

Answers (3)

Blaster
Blaster

Reputation: 9080

Try with style:

window.onload = function() {
    if(+(document.getElementById('main_image').style.width) > 700) {
      document.getElementById('main_image').style.width = '700px';
    }
};

If you have set width attribute then you would use getAttribute('width') and setAttribute(700) or directly width as you were doing. But if it comes from CSS, you will need to use style like shown above.

Upvotes: 1

Govind Malviya
Govind Malviya

Reputation: 13763

use "main_image" instead of main_image

<script>
if(document.getElementById("main_image").width > 700) {
document.getElementById("main_image").width = 700;
}
</script>
<img src="" id="main_image">

or you can use style also

document.getElementById("main_image").style.width = "700px";

Upvotes: 2

xivo
xivo

Reputation: 2054

Your issue is probably because you are running the script before the element exists on the page. Try reversing the script and the img tag.

Upvotes: 0

Related Questions