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;
}
unbindall
  • 514
  • 1
  • 13
  • 29
Angelo
  • 65
  • 1
  • 1
  • 10
  • 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). – Pointy Dec 28 '14 at 17:08
  • I edited it, im having a diferent name actually. – Angelo Dec 28 '14 at 17:12
  • Not really duplicate. As i do not know how to make the function do something else on second click. – Angelo Dec 28 '14 at 17:16
  • you just place a counter variable for each click and check for the counter value on each click.. – Lal Dec 28 '14 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"; – Angelo Dec 28 '14 at 17:28

2 Answers2

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()">
Shomz
  • 37,421
  • 4
  • 57
  • 85
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.

mshefiti
  • 103
  • 1
  • 7