0

I want to make a slider. I have two divs, left arrow and right arrow.

My idea is that when the left or the right arrow is clicked, the div that is active is hidden and the other view is displayed.
I am doing this with toggle(), and it hides the first view, but it doesn't show the second view.

And it needs to go smoothly, like a carousel.

Here is my JQuery:

$("#test2").hide();

$("#left").click(function(){
  $("#test1").toggle("slide", function(){
    $("#test1").show();
    $("#test2").hide();

  }, function(){
    $("#test2").show();
    $("#test1").hide();
  });
});

Here is an example of the HTML:

<div class="row">
  <div id="left></div>
  <div id="test1">image + text</div>
  <div id="test2">image + text</div>
  <div id="right"></div>
</div>
1
  • You are calling the exact opposite function of function "A" on callback (function "B")... And there is not delay in millisecond between parenthesis of show() and hide(). What do you expect as a result except nothing? Ever heard about "double negation" ? Commented Jun 3, 2017 at 2:20

2 Answers 2

2

Here is how a "toggle" works.
This example implies a CSS class toggle from "there" (applied on the element) or absent.

HTML:

<div class="row">
  <div id="left></div>
  <div id="test1">image + text</div>
  <div id="test2" class="hidden">image + text</div>
  <div id="right"></div>
</div>

CSS:

.hidden{
  display:none;
}

JS:

$("#left, #right").click(function(){
  $(".row div[id^='test']").toggleClass("hidden");
});

The ^= operator means "begin with".

Sign up to request clarification or add additional context in comments.

Comments

1

Looks like your JavaScript is incorrect. The changes below should get you where you want to be:

Demo Link

Working JSFiddle example

HTML

<div class="row">
  <div id="left">LEFT</div>
  <div id="test1">image + text 1</div>
  <div id="test2">image + text 2</div>
  <div id="right">RIGHT</div>
</div>

JavaScript

var $test1 = $("#test1");
var $test2 = $("#test2");

$("#test2").hide();

$("#left").click(function() {
  toggleViews($test2, $test1);
});

$("#right").click(function() {
  toggleViews($test1, $test2);
});

function toggleViews(viewToHide, viewToShow) {
  $(viewToHide).hide("slide", function() {
    $(viewToShow).show("slide");
  });
}

3 Comments

This worked, but I can click only once per arrow. I can't click multiple times on the left arrow. It works only on the first try.
Nope. This script works only for one click in each direction alternatively.
@Spirit_Scarlet Was hoping to get you a starting point and demonstrate how you can smoothly transition between elements. Will just go between the two div's but should be fairly easy to expand by using data-attributes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.