0

I want to activate CSS using JS. Let's say I have this code, and I want to enlarge a picture at first click and then send it to the right after at the second click, but it's not working. Is the function correct?

How can I use JavaScript to control the CSS of an element?

<script>
    function function(){
        var house = document.getElementById("house");
            if(this.className == "mystyle")
                this.className = "mystyle2";
            else
                this.className = "mystyle";
    }
</script>

 <a href="#" style="text-decoration: none"><img src="casa1.jpg" id="house" width="200" height="150" onclick="function()">

I want it to activate this CSS:

.mystyle {
position: absolute;
left: 50%;
margin-left: -100px;
}

.mystyle2{
    float: right;
}
5
  • 4
    You can't give a function the name "function". You should see an error in the browser console if you check (which you should). Commented Dec 28, 2014 at 17:08
  • I edited it, im having a diferent name actually. Commented Dec 28, 2014 at 17:12
  • Not really duplicate. As i do not know how to make the function do something else on second click. Commented Dec 28, 2014 at 17:16
  • you just place a counter variable for each click and check for the counter value on each click.. Commented Dec 28, 2014 at 17:19
  • I tried it like this, but doesnt work : function functie(){ var house = document.getElementById("house"); var count; count++; if(count%2 == 1) house.className = "mystyle"; else house.className = "mystyle2"; Commented Dec 28, 2014 at 17:28

2 Answers 2

1

Your code is good, but your scope is bad. Instead of this inside the function, you need to use house:

function function1() {
  var house = document.getElementById("house");
  if (house.className == "mystyle")
    house.className = "mystyle2";
  else
    house.className = "mystyle";

}
.mystyle {
  position: absolute;
  left: 50%;
  margin-left: -100px;
}

.mystyle2 {
  float: right;
}
  <img src="http://images.clipartpanda.com/cute-house-clipart-house_clipart_12.gif" id="house" width="200" height="150" onclick="function1()">

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Worked great.
1

Replace this, with house. In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When you define your function function1() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript. Otherwise looks good.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.