Rushabh Shah Rushabh Shah - 12 days ago 6
Javascript Question

jQuery function is not working as per my expectation

in my HTML I have two buttons one is previous and second is next button. it will be display next slide by clicking next button. it will be display previous slide by clicking prev button. I didn't know but sometime I need to click two times for going on previous slide. Can you please tell me why it happening? and How can I resolve it? I am weak in English so please apologize me if I made any Grammatical or Spelling mistakes.

jQuery code:

$("#next").click(function(){
var pagenumber = $(this).data("page")-1;
$("#page"+pagenumber).addClass("hide");
$("#page"+$(this).data("page")).removeClass("hide");
if($(this).data("page") == 3){
$("#next").addClass("hide");
}
else{
$('#next').data('page', $(this).data("page")+1);
$('#prev').data('page', $(this).data("page")-1);
}
if($("#prev").data("page") > 0 && $("#prev").hasClass("hide")){
$("#prev").removeClass("hide");
}
});
$("#prev").click(function(){
var pagenumber = $(this).data("page")+1;
$("#page"+pagenumber).addClass("hide");
$("#page"+$(this).data("page")).removeClass("hide");
if($(this).data("page") == 0){
$("#prev").addClass("hide");
}
else{
$('#prev').data('page', $(this).data("page")-1);
$('#next').data('page', $(this).data("page")+1);
}
if($("#next").data("page") < 3 && $("#next").hasClass("hide")){
$("#next").removeClass("hide");
}
});


Html code:

<div style="text-align:left"><a id="prev" class="hide" data-page="0">< PREV</a></div>
<div style="text-align:right"><a id="next" data-page="1">NEXT ></a></div>

A.J A.J
Answer

First of all you need to optimize you code, utilized a techique jQuery selector caching

var $next = $("#next");
var $prev = $("#prev");
$next.click(function() {
  var pagenumber = $next.data("page") - 1;
  $("#page" + pagenumber).addClass("hide");
  $("#page" + $next.data("page")).removeClass("hide");
  if ($next.data("page") == 3) {
    $next.addClass("hide");
  } else {
    $next.data('page', $next.data("page") + 1);
    $prev.data('page', $next.data("page") - 1);
  }
  if ($prev.data("page") > 0 && $prev.hasClass("hide")) {
    $prev.removeClass("hide");
  }
});
$prev.click(function() {
  var pagenumber = $prev.data("page") + 1;
  $("#page" + pagenumber).addClass("hide");
  $("#page" + $prev.data("page")).removeClass("hide");
  if ($prev.data("page") == 0) {
    $prev.addClass("hide");
  } else {
    $prev.data('page', $prev.data("page") - 1);
    $next.data('page', $prev.data("page") + 1);
  }
  if ($next.data("page") < 3 && $next.hasClass("hide")) {
    $next.removeClass("hide");
  }
});