Function for Text Hiding: Is there a way to conceal the text when the user slides to the left or right of the comparison slider

My comparison function allows users to slide left and right to view before and after images, functioning well thanks to the code I found on CodePen.

However, I have one issue - I want text to appear on the left and right sides of the image, disappearing as the slider approaches and reappearing when it moves away. The same functionality should apply to both sides.

Does anyone have any suggestions on how I can achieve this? You can view the code here.

Thank you for your help!

$(document).ready(function () {
    $('.ba-slider').each(function () {
        var cur = $(this);
        
        // Adjust the slider
        var width = cur.width() + 'px';
        cur.find('.resize img').css('width', width);
        
        // Bind dragging events
        drags(cur.find('.handle'), cur.find('.resize'), cur);
    });
});

// Update sliders on resize
$(window).resize(function () {
    $('.ba-slider').each(function () {
        var cur = $(this);
        var width = cur.width() + 'px';
        cur.find('.resize img').css('width', width);
    });
});

function drags(dragElement, resizeElement, container) {
    // Dragging event on mousedown
    dragElement.on('mousedown touchstart', function (e) {
        dragElement.addClass('draggable');
        resizeElement.addClass('resizable');

        // Determine mouse or touch event
        var startX = (e.pageX) ? e.pageX : e.originalEvent.touches[0].pageX;

        // Get initial position
        var dragWidth = dragElement.outerWidth(),
            posX = dragElement.offset().left + dragWidth - startX,
            containerOffset = container.offset().left,
            containerWidth = container.outerWidth();

        // Set limits
        minLeft = containerOffset + 10;
        maxLeft = containerOffset + containerWidth - dragWidth - 10;

        // Calculate drag distance
        dragElement.parents().on("mousemove touchmove", function (e) {
            var moveX = (e.pageX) ? e.pageX : e.originalEvent.touches[0].pageX;
            leftValue = moveX + posX - dragWidth;

            // Prevent going off limits
            if (leftValue < minLeft) {
                leftValue = minLeft;
            } else if (leftValue > maxLeft) {
                leftValue = maxLeft;
            }

            widthValue = (leftValue + dragWidth / 2 - containerOffset) * 100 / containerWidth + '%';

            // Set new values for the slider and handle
            $('.draggable').css('left', widthValue).on('mouseup touchend touchcancel', function () {
                $(this).removeClass('draggable');
                resizeElement.removeClass('resizable');
            });
            $('.resizable').css('width', widthValue);
        }).on('mouseup touchend touchcancel', function () {
            dragElement.removeClass('draggable');
            resizeElement.removeClass('resizable');
        });

        e.preventDefault();
    }).on('mouseup touchend touchcancel', function (e) {
        dragElement.removeClass('draggable');
        resizeElement.removeClass('resizable');
    });
}

Cheers!

Answer №1

If the slider reaches the maximum value, the label will be hidden; otherwise, it will be displayed as a block.

if (leftValue === minLeft)
  document.getElementById("leftElement").style.display = 'none';
else      
  document.getElementById("leftElement").style.display = 'block';`

To make it more visible for demonstration purposes, I have adjusted the maximum and minimum values to +-80.

$(document).ready(function() {
  $(".ba-slider").each(function() {
    var cur = $(this);
    // Adjust the slider
    var width = cur.width() + "px";
    cur.find(".resize img").css("width", width);
    // Bind dragging events
    drags(cur.find(".handle"), cur.find(".resize"), cur);
  });
});

// Update sliders on resize.
$(window).resize(function() {
  $(".ba-slider").each(function() {
    var cur = $(this);
    var width = cur.width() + "px";
    cur.find(".resize img").css("width", width);
  });
});

function drags(dragElement, resizeElement, container) {
  // Initialize the drag event on mousedown.
  dragElement
    .on("mousedown touchstart", function(e) {
      dragElement.addClass("draggable");
      resizeElement.addClass("resizable");

      // Check if it's a mouse or touch event and pass along the correct value
      var startX = e.pageX ? e.pageX : e.originalEvent.touches[0].pageX;

      // Get the initial position
      var dragWidth = dragElement.outerWidth(),
        posX = dragElement.offset().left + dragWidth - startX,
        containerOffset = container.offset().left,
        containerWidth = container.outerWidth();

      // Set limits
      minLeft = containerOffset + 80;
      maxLeft = containerOffset + containerWidth - dragWidth - 80;


      // Calculate the dragging distance on mousemove.
      dragElement
        .parents()
        .on("mousemove touchmove", function(e) {
          // Check if it's a mouse or touch event and pass along the correct value
          var moveX = e.pageX ? e.pageX : e.originalEvent.touches[0].pageX;

          leftValue = moveX + posX - dragWidth;

          // Prevent going off limits
          if (leftValue <= minLeft) {
            leftValue = minLeft;
          } else if (leftValue > maxLeft) {
            leftValue = maxLeft;
          }
        
          if (leftValue === minLeft)
             document.getElementById("leftElement").style.display = 'none';
          else      
             document.getElementById("leftElement").style.display = 'block';
        
         if (leftValue === maxLeft)
            document.getElementById("rightElement").style.display = 'none';
         else      
            document.getElementById("rightElement").style.display = 'block';


          // Translate the handle's left value to masked divs width.
          widthValue =
            (leftValue + dragWidth / 2 - containerOffset) *
              100 / 
              containerWidth +
            "%";

          // Set the new values for the slider and the handle.
          // Bind mouseup events to stop dragging.
          $(".draggable")
            .css("left", widthValue)
            .on("mouseup touchend touchcancel", function() {
              $(this).removeClass("draggable");
              resizeElement.removeClass("resizable");
            });
          $(".resizable").css("width", widthValue);
        })
        .on("mouseup touchend touchcancel", function() {
          dragElement.removeClass("draggable");
          resizeElement.removeClass("resizable");
        });
      e.preventDefault();
    })
    .on("mouseup touchend touchcancel", function(e) {
      dragElement.removeClass("draggable");
      resizeElement.removeClass("resizable");
    });
}
.rinse-away-container {
  margin-bottom: 8rem;
}
@media (min-width: 768px) {
  .rinse-away-container {
    margin-bottom: 10rem;
  }
}
@media (min-width: 992px) {
  .rinse-away-container {
    margin-bottom: 15rem;
  }
}
.ba-slider {
  position: relative;
  overflow: hidden;
  max-width: 1045px;
  margin: 5rem auto 0;
}
.ba-slider img {
  width: 100%;
  display: block;
}
.ba-slider .label-left,
.ba-slider .label-right {
  position: absolute;
  bottom: 0;
  z-index: 2;
  padding: 1rem;
  color: white;
}
.ba-slider .label-right {
  right: 0;
}
.resize {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 50%;
  overflow: hidden;
}
.handle {
  position: absolute;
  left: 50%;
  top: 0;
  bottom: 0;
  width: 1px;
  margin-left: -2px;
  background: #fff;
  cursor: ew-resize;
}

.handle:after {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 10px;
  height: 64px;
  margin: -32px 0 0 -5px;
  content: "";
  color: white;
  text-align: center;
  background: #fff;
  -webkit-transition: all 0.3s ease;
  transition: all 0.3s ease;
}

.draggable:after {
  width: 30px;
  height: 64px;
  margin: -32px 0 0 -15px;
}
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <title></title>
</head>

<body>
  <div class="rinse-away-container">
    <div class="container rinse-away-content">
      <div class="compare-image-container">
        <div class="ba-slider">
          <img src="https://i.ibb.co/8cC5xQh/test1.png" alt="Test 1">
          <div id="leftElement" class="label-left">Text Left</div>
          <div class="resize">
            <img src="https://i.ibb.co/FkQQJ8j/test2.png" alt="Test 2">
          </div>
          <div id="rightElement" class="label-right">Text Right</div>
          <span class="handle"></span>
        </div>
      </div>
    </div>
  </div>

  <!-- JavaScript -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</body>

</html>

Answer №2

Ensure to monitor the direction in which your mousemove function is moving, and accordingly decide whether to display or hide the labels.

dragElement
  .parents()
  .on("mousemove touchmove", function(e) {
  // Determine if it's a mouse or touch event and retrieve the correct value
  var moveX = e.pageX ? e.pageX : e.originalEvent.touches[0].pageX;
  if(moveX < startX) {
    //move left
    $('.label-left').hide();
    $('.label-right').show();
  }else{
    //move right
    $('.label-right').hide();
    $('.label-left').show();
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to maintain data consistency among controllers in Angular by utilizing the rootScope, only to encounter persistent issues with

I am facing an issue with displaying the admin status at the top of all pages for a user who successfully logs in as an admin. Here is my code snippet: <!-- nav bar --> <div> <span ng-show="$root.isAdmin">(ADMIN)</span> </di ...

Enveloping elements with jQuery

I am currently utilizing AJAX with jQuery to retrieve some HTML content, and here is the success function: function handleSuccess(response) { var searchTerm = $("#input").val(); // Convert string of HTML to object var anchors = $('<d ...

Upon selecting the display image option

Here is a jsfiddle file provided for your reference. I am attempting to create a functionality where upon clicking buttons (1,2,3,4), the corresponding image shows up and overlaps with any previously displayed images. I have tried using the following code ...

React-Native-SVG encountered an error: Invariant Violation - the component "RNSVGGroup" could not be found in the UIManager

Trying to create an SVG in React-Native using react-native-svg. I have set up a React-Native-CLI. After doing some research, I attempted to solve the issue on my own and found something useful. I tried running cd ios && pod install. I wasn't ...

What is the process of invoking a Java method through AJAX on a website?

I am trying to figure out how to call the Java method getMessage() from a jar file whenever a button on my webpage is clicked. Can anyone help me achieve this? File name: index.html <!doctype html> <html> <head> <meta charset="utf-8" ...

Eliminating unnecessary gaps caused by CSS float properties

I need help figuring out how to eliminate the extra space above 'Smart Filter' in the div id='container_sidebar'. You can view an example of this issue on fiddle http://jsfiddle.net/XHPtc/ It seems that if I remove the float: right pro ...

The status code is not recognized: ERROR_UNEXPECTED_FILE - Multer for Node.js

Looking to develop a form that includes a field for uploading multiple images, similar to what you would find on a real estate website. While testing in Postman, I configured the body to form-data and attempted to post two files to http://localhost:8080/a ...

Exploring MongoDB's grouping capabilities with a touch of Lodash chain and groupBy

I have a lodash function that groups and returns an array like this [{ key: '00001', amount: 135, request: [ false, false ] }] I am looking for a way to check if the request contains any value using MongoDB aggregate. Currently, I can ...

Utilize sw-precache and Gulp to cache API calls and store backend server images on the client

I am new to using sw-precache with gulp in my application. I have developed a web app using AngularJS that retrieves information from our backend Node.js application. In the backend application, I have implemented the sw-precache feature to create an offli ...

Exploring the use of nested arrays in JavaScript: accessing elements in different modules

Could you provide an example of a nested array that can be accessed across ES6 module boundaries with setter and getter methods from a dependent module? While setter methods work fine, invoking getter methods across module boundaries always results in: T ...

Retrieve and present JSON information (object, array) using a service provider in Ionic 2 with TypeScript and Angular 2

I am currently delving into Angular 2 and Ionic 2 (not to forget about NodeJS and TypeScript). For testing purposes, I have a list of users available here. Eventually, I will be fetching real user data from an API connected to my database. To handle this ...

Retrieve the HTML or text immediately following the input tag within a label using jQuery

There is a label that looks like this: <label> <input type="checkbox" value="160">160 </label> or it could look like this: <label> <input type="checkbox" value="-160-"><del&g ...

Does reducing the number of HTML, PHP, or CSS files truly have a significant impact on improving a webpage's performance, or is it just a minor factor?

Discovering a new HTML minifier on Ajaxian got me thinking - is minimizing HTML, PHP, or CSS files truly a significant improvement for webpages? Would shrinking files that are 100 lines long on average make a noticeable impact? ...

What is causing my AJAX function to malfunction and throwing an exception for undefined data objects?

I am having trouble with my ajax query in my code. Even though it is returning the required data, it is not displaying properly within the HTML code. I have a common header and footer (PHP) for all other files. Despite my efforts to resolve this issue by s ...

In JavaScript, use a regular expression to replace all instances of %2F with %

Looking for a JavaScript/regex solution to transform %2F into %21. This will allow me to successfully pass forward slashes through a GET parameter after using encodeURIComponent() on a URL. Once the data reaches the server, I'll convert back from ! ...

The React application is functioning properly; however, during compilation, it continually displays an error stating that the module cannot be found

Compilation Failed. Error: Module not found, unable to resolve the specified path. webpack compiled with 1 error I was hoping for a successful compilation, but unfortunately encountered an error. It's perplexing as the application is functioning co ...

The response value in Uploadify is consistently returning as undefined when used with ASP.NET

Currently, I am utilizing Uploadify to upload a series of images with the assistance of ASP.NET. To transmit the outcome of the upload back to JavaScript, I have employed Response.WriteFile() in ASP.NET. I am adhering to the guidance provided in the docu ...

Is there a way to showcase AJAX responses in the exact sequence they were dispatched, all without relying on queuing or synchronous requests?

I'm facing a challenge with sending out multiple getJSON() requests to a remote server in order to retrieve images. The issue is that the responses arrive asynchronously, causing them to be displayed in a mixed-up order. While I could make the reques ...

What is the best way to add all the items from an array to a div element?

I am currently facing an issue where only the last object in my array is being added to my div using the code below. How can I modify it to add all objects from the array to my div? ajaxHelper.processRequest((response: Array<Vehicle.Vehicle>) ...

How can I assign a variable to a JSON value with spaces in its name?

I have a variable let importantData = data[selectedItem].attributes[0]; I need to link it to various information within a JSON dataset in order to retrieve the value when I execute the following code, everything works smoothly let electricityPlant = u ...