Problem with two clicks - Javascript function

Asked

Viewed 263 times

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 in the second click, after that it works correctly in the first click. Why it happens?

  • tried <a href="#" onclick="zoom('example','examplo2','examplo3');">Calls function</a>?

  • Yes, but I get the same result.

1 answer

1


Everything works well, 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 such:

 el.style.width = "500px";

Then, in a second click, the width is no longer 360px, but yes 500px, what makes him fall in the else.

Note that you have a parole conflict where you own this if:

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

within this:

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

What does that mean?

Either the width is 500px or it’s 360px - the same element can’t handle two sizes simultaneously; at the end of the day, that’s illogical - it doesn’t make any sense.

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

I don’t know exactly what your goal is or what outcome you want to achieve, but there’s no technical problem there, just logical or conceptual. If my answer is not enough, give more details of your problem.

  • Hello, William. Thank you for the reply. I modified a little the example you sent me, now it is demonstrating my situation. http://jsfiddle.net/qGbw6/17/ .

  • You just need to perform the function zoom() to invoke its properties. Click here and understand.

  • I understood, in case it is necessary to preload the function before clicking the button. Thank you.

  • @Exact Matheus. ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.