Two-click problem - JavaScript function

1

I'm using this simple function to conditionally change CSS in Javascript:

function zoom(obj, icon, menu) {
  var el = document.getElementById(obj);
  var img = document.getElementById(icon);
  var men = document.getElementById(menu);
  var men2 = document.getElementById(menu + "2");
  if (el.style.width === "360px") {
    el.style.width = "500px";
    el.style.height = "308px";
    men.style.width = "500px";
    men2.style.width = "500px";
    if (el.style.width === "500px") {
      img.src = "img/icons/png/minimize1.png";
    }
  } else {
    el.style.width = "360px";
    el.style.height = "222px";
    men.style.width = "360px";
    men2.style.width = "360px";
    if (el.style.width === "360px") {
      img.src = "img/icons/png/expand.png";
    }
  }
}

It is used to change the size of 3 elements with different Id's.

But when I use the function in a link:

<a href="javascript:zoom('exemplo','exemplo2','exemplo3');">Chama função</a>

The function is only applied on the second click, after that it works correctly on the first click. Why does this happen?

    
asked by anonymous 22.07.2014 / 04:13

1 answer

1

Everything works fine, however, the conditional flow seems to me out of the logic you want.

In the following fragment, you check whether the width of el is 360px :

 if (el.style.width === "360px") { }

If the width is exactly 360px, then you declare a new width for it:

 el.style.width = "500px";

Then, in a second click, the width is no longer 360px , but 500px , which causes it to fall in else .

Note that you have a conditional conflict, where you have this if :

 if (el.style.width == "500px") { }

within this:

 if (el.style.width === "360px") { }

What does this mean?

Either the width is 500px or it is 360px - the same element can not handle two sizes simultaneously; in the end, this is illogical - it does not make any sense.

With your logic, we can represent your scenario with this jsFiddle . There is the organic difference of execution of your function through a listener, but otherwise I keep everything the same.

I do not know exactly what your goal or what result you want to get, but there is no technical problem there, just logical or conceptual. If my answer is not enough, give more details of your problem.

    
22.07.2014 / 04:31