Belgacem Ksiksi Belgacem Ksiksi - 4 years ago 75
HTML Question

JavaScript - function not working

With the code below I want to the function to run when it called , for now nothing is happening, does the name of the function unacceptable?

function zoom(d) {
if (d == "in")
$("#animation_border").css("height", ($(window).height() * 100 / 85) + "px");
else
$("#animation_border").css("height", (canvas.width * 0.719) + "px");

}

if ($(window).width() >= 619) {
zoom("out");
} else {
zoom("in");
}
}

Answer Source

I'm assuming you want to call the zoom() function when the window is resized. If so, we can use the $(window).resize() event to get what you want:

function zoom(d) {
  if (d == "in") {
    // Your code here
  } else {
    // Your code here
  };
}

// Automatically called when window is resized
$(window).resize(function() {
  if ($(window).width() >= 619) {
    zoom("out");
  } else {
    zoom("in");
  };
})

Working JSFidde: https://jsfiddle.net/209m4esk/2/

As a side note, it would be more efficient to compare a boolean in your zoom() function rather than a string. We should also allow for invalid parameters given to the function. i.e:

function zoom(zoomIn) {
  if (typeof(zoomIn) !== "boolean") {
      console.log("Parameter given is not a boolean.");
  } else if (zoomIn) {
    // Your code here
  } else {
    // Your code here
  };
}

So then you'd simply call zoom(true) to zoom in, and zoom(false) to zoom out.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download