A versatile CSS and JavaScript slider component that is designed to be reused multiple times within a single webpage

Looking to create a CSS/jQuery slider that can be used multiple times on one HTML page.

I have a client who wants sliders as category links, but I'm struggling to get it working as a single slider on a page. Can someone review the code and point out what I might be doing wrong? I need help organizing the project efficiently.

If anyone could outline the steps to achieve this without providing actual code, I would greatly appreciate it.

var intervalid = {};

$(document).ready(function() {

  function slide(elem) {
    sliderid = $("#" + elem);
    
    sliderid.find(".main_image").on("mouseover", function() {
      $(this).find(".main-desc").css("display", "block");
    });

    sliderid.find(".main_image").on("mouseleave", function() {
      $(this).find(".main-desc").css("display", "none");
    });

    intervalid[elem] = setInterval(slidecycle(elem), 4500);
  }

  function testcycle(elem) {
    console.log("cycle");
  }

  function slidecycle(elem) {
    sliderid = $("#" + elem); 
    
    var lastimage = sliderid.find(".imgs_holder > .image:last").hasClass("active"); 
    var currentimage = sliderid.find(".imgs_holder > .image.active"); 

    if (lastimage) {
      var nextimage = sliderid.find(".image_thumb > .image:first")
    } else {
      var nextimage = sliderid.find(".imgs_holder > .image.active").next();
    }

    $(currentimage).removeClass("active");
    $(nextimage).addClass("active");

    var imgAlt = $(nextimage).find('img').attr("alt");
    var imgSrc = $(nextimage).find('img').attr("src");
    var imgTitle = $(nextimage).find('a').attr("href");
    var imgDesc = $(nextimage).find('.desc').html();
    var imgDescHeight = sliderid.find(".main_image").find('.main-desc').height();

    $(nextimage).css("background-color", "#efefef");
    
    sliderid.find(".main_image .main-desc").animate({
      opacity: 0,
      marginBottom: -imgDescHeight
    }, 250, function() {
      sliderid.find(".main_image .main-desc").html(imgDesc).animate({
        opacity: 0.85,
        marginBottom: "0"
      }, 250);
      sliderid.find(".main_image img").attr({
        src: imgSrc,
        alt: imgAlt,
        name: imgAlt
      });
    });
  }

  slide("slider1");
  slide("slider2");
});
html {
  font-family: arial;
  font-size: 1em;
}

.imgs_holder {
  width: 100%;
}

/* Additional styling */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slideshow" id="slider1">
  <!-- Slider content here -->
</div>
<div class="slideshow" id="slider2">
  <!-- Slider content here -->
</div>

Answer №1

Your code contains multiple errors that need to be addressed.

Firstly, it is recommended to name jQuery variables with a dollar sign ($) at the beginning. For example, var $test = $(".test");. This way, unnecessary jQuery calls can be avoided.

...
var nextimage = sliderid.find(".image_thumb > .image:first");
...
var imgAlt = $(nextimage).find('img').attr("alt");
...

The nextimage variable is already a jQuery object, so using $() on it is redundant.

Secondly, when checking for the current element with the class active and the next element as the following element after the current one, it's essential to consider scenarios where there may not be an element with the class active initially, such as in your second slider.

This scenario should be taken into account.

Thirdly, when using the setInterval function, make sure to call it like this:

setInterval(function() {
    slidecycle(elem);
}, 4500);

Last but not least, try to minimize jQuery calls as they consume time and memory. Avoid repeating actions for the same element more than once by saving that element to a variable.

For instance:

var $main = sliderid.find(".main_image"),
    $mainDesc = $(this).find(".main-desc");

$main.on("mouseover", function() {
  //alert("hover");
  $mainDesc.css("display", "block");
});

$main.on("mouseleave", function() {
  //alert("hover");
  $mainDesc.css("display", "none");
});

Or

var $mainDesc = $(this).find(".main-desc");

sliderid.find(".main_image").on("mouseover", function() {
    //alert("hover");
    $mainDesc.css("display", "block");
  })
  .on("mouseleave", function() {
    //alert("hover");
    $mainDesc.css("display", "none");
  });

Here is a functional example:

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

What is the proper way to declare a Type for a JSX attribute in Google AMP that utilizes square brackets?

When utilizing AMP's binding feature, you must apply specific attributes that encapsulate an element's property with square brackets and connect it to an expression. An example from AMP is shown below: <p [text]="'Hello ' + foo"> ...

Image Animation Using a Rotational Control (HTML/JavaScript/...)

I am interested in achieving a specific effect with a series of images that transition from dark to light. My idea is to have a dial or slider underneath or over the frame so that when it is moved to the left, the black image is displayed, and when moved t ...

Is there a more efficient method for invoking `emit` in Vue's Composition API from an external file?

Is there a more efficient way to access the emit function in a separate logic file? This is my current approach that is functioning well: foo.js export default (emit) => { const foo = () => { emit('bar') }; return { foo }; } When ...

Steps for placing a second pie chart alongside the initial one within a Bootstrap card

Is it possible to have two pie charts with different values using chart.js? I attempted to duplicate the script for the first chart to create a second one, but it did not display correctly. Why is the second pie chart not showing up? $(document).ready(fu ...

Images with full-width will scroll horizontally

Is there a way to fix the horizontal scroll issue? <!DOCTYPE html> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https:// ...

Looking for assistance in creating an html page with a rotating CSS div containing unordered lists and list items

I am sharing the HTML content of my test page that I am looking to customize similar to some websites I have come across. My goal is to create a rotating div with an unordered list (ul li), where only three divs are displayed at a time while the rest remai ...

An innovative approach to loading tabs dynamically using Materialize CSS

I have a situation where I am dynamically generating a set of tabs when the page loads, but for some reason the on function is not recognizing it. How can I fix this issue? Here is the current code: HTML <div class="row"> <div class="col s12 ...

Ensure that you include validation in the ajax request when loading the message content from a separate file

ajax code for adding data to the database <script type="text/javascript"> $(function() { $(".submit_button").click(function() { var textcontent = $("#content").val(); var dataString = 'content='+ textcontent; if(textcontent=='') ...

Display loading spinners for multiple ajax requests

At the moment, I am displaying spinners using the ajax setup method call: (function() { $.ajaxSetup({ beforeSend: showLoader, complete: hideLoader, error: hideLoader }); })(); While this setup is functioning properly, the ...

Is there a way to activate ng-class on only a single element?

In my code, I am using ng-repeat and ng-class for each element to select elements and add borders for the selected ones. <div class="main-block_channel_create"> <section class="parent_messageList cancelDelete"> <div id="section_animate" ...

Using javascript, retrieve the JSON values for each level

I need help using a recursive function in JavaScript to retrieve the last key value pair from a simple JSON object. Here is an example JSON object: { 'a': { 'b': { 'c': 12, 'd': 'Hello World& ...

Using HTML in jQuery or JavaScript: A Step-by-Step Guide

Here's the deal - I've got a bunch of buttons. https://i.sstatic.net/839MH.png What I want is, when the 4th button is clicked, to trigger a select menu option like this: The outcome I'm aiming for after clicking the button is https://i.ss ...

What is the best way to adjust the position of an image background within a container without affecting the container's own placement?

While working on a registration form, I encountered an issue with moving the background image within a container. Despite adding position: relative and using top: with a negative value to shift the image, the entire container moved instead of just the back ...

ACE editor error: Attempted to access the 'getValue' property of an undefined object

In the process of developing an Angular markdown editor, I have integrated the ACE editor as a code editor. The npm package for ACE editor can be found here. You can access a codesandbox version of the project here. My current challenge involves retrievi ...

Which chat applications are compatible with cakephp for seamless integration?

Do you have any suggestions for chat applications that integrate well with CakePHP? Ideally, something similar to Facebook Chat that is also customizable. Thank you, JRubins ...

What is the default state of ng-switch in AngularJS?

I am completely new to using AngularJS and I have a question about setting a default ng-switch state in the following Plunkr. Currently, I can only get it to work when clicking, but ideally the menu should be displayed automatically if the user button is t ...

The initial row's Id will be used as the Id for all subsequent rows within a JSON object

After dragging a tr in a table and confirming by clicking a button, I need the order list to be updated in the database. To achieve this, I created a JSON object where I intend to save the ids and their corresponding new orders. The issue I am facing is t ...

Angular 2 keypress validation: Ensuring data integrity through real-time input verification

I am currently facing an issue with implementing number validation in my Angular2 project. I am struggling to replicate the JavaScript code provided below. Here is the HTML: <input type="text" class="textfield" value="" id="extra7" name="extra7" onkeyp ...

Having trouble with localstorage.setitem function in Angular?

Check out the function below. I can see an object in the console.log using res: login2(){ console.log(this.user_form_value); console.log(this.password_form_value); this._loginService.login(this.user_form_value, this.password_form_value).subscr ...

The Mustache feature is bringing back old information alongside fresh updates

Currently, I am utilizing mustache.js to display JSON data in a template. However, I have encountered an issue where Mustache is appending previous response data along with the new one when I make a $.ajax post request. How can I prevent Mustache from reta ...