Click here to Skip to main content
15,902,198 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have image Width=200, Height=200. I need after every click on image, that image increase with 50px, and when it will become 500px, it must decrease with 50px, and when it will become 200px, again it must increase with 50px and so on.
How can i do it?

What I have tried:

I have tried like this but it's wrong.

JavaScript
function Increase_Decrease() {
    var w = document.getElementById("img").width;
    var h = document.getElementById("img").height;
    if (w <= 500 && h <= 500) {
        var w = document.getElementById("img").width += 50;
        var h = document.getElementById("img").height += 50;
    } else {
        var w = document.getElementById("img").width -= 50;
        var h = document.getElementById("img").height -= 50;
    }
}
Posted
Updated 3-Jul-18 22:37pm

an improved version
JavaScript
<pre>var increasing=1;
var min_width=200;
var change=50;
var max_lenght=500;
function Increase_Decrease() {

	document.getElementById("img").width += change*increasing;
	document.getElementById("img").height += change*increasing;
	if(document.getElementById("img").width >= max_lenght) {
		increasing=-1;
	} else if(document.getElementById("img").width <= min_width) {
		increasing=1;
	}
}
 
Share this answer
 
What your code will do is resize 200 -> 250 -> 300 -> 350 -> 400 -> 450 -> 500 -> 450 as intended, but after that, the size is less than 500, so it will increase again. It will oscillate 500 -> 450 -> 500 -> 450 -> 500 -> 450, etc.
You need to remember whether you are in a going up or a going down phase. The simplest way (other folks may disagree) is to add an attribute to the image tag. e.g.

function Increase_Decrease() {
    var img = document.getElementById("img");
    var w = img.width;
    var h = img.height;

    if (w <= 200 && h <= 200) {
       img.changeSize = 50;   // At bottom of range. So must now go up
    } else if (w >= 500 && h >= 500) {
       img.changeSize = -50;    // At top of range. So must now go down again
    }

    img.width += 1 * img.changeSize;   // Attributes are strings. Multiply by 1 is one of several ways to quickly convert it to a number
    img.height += 1 * img.changeSize;
}


This is all from the top of my head. It is totally untested.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900