Here is the code snippet that I’m trying to make better
var slider = $("#slider");
slider.on("click", "#up", function () {
var ul = $(".slider-small-box");
var marginTop = ul.css("margin-top");
var ulHeight = ul.height();
if(ulHeight + parseInt(marginTop, 10) <= 555) {
ul.css("marginTop", "0px");
} else {
var s = parseInt(marginTop, 10);
s = s - 185;
ul.css("marginTop", s + "px");
}
});
The problem with the above code is that it have to search the DOM for “.slider-small-box” everytime the “up” button is clicked (the “up” button is a button tag like this: <button id="up">UP</button>
). Everything is working fine and smoothly but I want to write better code.
You might be asking “So why don’t you just reference the “.slider-small-box” element outside of the click event?”. The reason is that the element “.slider-small-box” and the button “#up” are both dynamically inserted into the page using AJAX and because of that I can’t reference them outside the “click” event function.
I’ve tried to find a solution for that and I stumbled upon jQuery deferreds. Here is how the code looks like when I use jQuery deferreds:
$.sliderResults().done( function () {
var ul = $(".slider-small-box");
var marginTop = ul.css("margin-top");
var ulHeight = ul.height();
var up = $("#up");
up.on("click", function () {
if(ulHeight + parseInt(marginTop, 10) <= 555) {
ul.css("marginTop", "0px");
} else {
var s = parseInt(marginTop, 10);
s = s - 185;
ul.css("marginTop", s + "px");
}
});
}
The problem with the above code is that the “click” event can only be executed once, so that when I click the “up” button again nothing happens.