0

I am beginner in JavaScript and it looks like I don't understand quite good if statements. I want to change background-color of div from red to blue when div becomes 500px. Hi will get 500px when I click anywhere on body tag. Here is the code:

<!DOCTYPE html>
<html>

<head>
  <title>Page Title</title>
</head>

<body onclick="Go();" >
<div id="test"></div>

<style>
#test {
width: 300px;
height: 250px;
background-color: red;
}
</style>
<script>
function Go() {
var div_test = document.getElementById('test').style;
div_test.width="500px";
}

if (document.getElementById('test').style.width="500px") {document.getElementById('test').style.cssText="background-color:blue";}

</script>
</body>

</html>

It looks like that browser instead of understanding part in brackets of if statement as conditional "when that happened", he just create that state/style of div. When page loads div is already blue.

1
  • In your if statement you're setting the width to 500 with a single =, try === for a comparison Commented Mar 12, 2015 at 13:50

1 Answer 1

1

In your statement

if(document.getElementById('test').style.width="500px")

it should be

if(document.getElementById('test').style.width == "500px")

In javascript you have to user == or === as operator for comparing values

In addition, if you want to have a blue background when the element width became 500px you will have two options

1- Add an interval

function Go() {
    var div_test = document.getElementById('test').style;
    div_test.width="500px";
}

var interval = setInterval(function() {
    if (document.getElementById('test').style.width="500px") { 
        document.getElementById('test').style.cssText="background-color:blue";
        clearInterval(interval);
    }
}, 500);

2 - just move your statement to your Go() Function (you will not need the if statement anymore)

function Go() {
    var div_test = document.getElementById('test').style;
    div_test.width="500px";
    document.getElementById('test').style.cssText= " background-color:blue";
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. But still I don't get blue color for div when he become 500px.
You have to rethink your logic. You can have a timer checking when the width become 500px or you can move the block straight to the if statement.
Could you give me an example?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.