What is the appropriate way to link the right function to the slideshow button?

I'm having trouble creating a functional slideshow with buttons. Each button should display its corresponding div when clicked, while the slideshow continues to function as normal.

View the demo here: http://jsfiddle.net/sabeti05/dsagcc5u/

HTML

    <div id="slideshow">
       <div class=" hide block">
        one
       </div>
       <div class="hide">
        two
       </div>
       <div class="hide">
        three
       </div>
    </div>
    <button class="one">one</button>
    <button class="two">two</button>
    <button class="three">three</button>

CSS

body{text-align:center}
#slideshow {
    height: 40px;
    margin: 0 auto;
    position: relative;
    width: 100px;
}
#slideshow > div {
    position: absolute;
}
.hide {
    display: none;
}
.block {
    display: block;
}

jQuery

$(document).ready(function(){
    setInterval(function() {
      $('#slideshow > div.block')
        .removeClass("block")
        .next()
        .addClass("block")
        .end()
        .appendTo('#slideshow');
    },  1000);
});

Answer №1

Check out the changes I implemented in your demo.

You came up with a clever trick by rotating DOM elements, but this causes the divs to lose their connection with the buttons. Instead, I recommend leaving the elements in place and using the next() method for selection. If the selection is empty, you can use first() of the siblings.

Furthermore, the markup needs to be adjusted so that buttons have type="button" (to avoid their default type of submit) and they should be contained within the #controls div.

By binding a single event listener to the container's click event on the button element, you can easily find its index in the container and display the corresponding div using jQuery selectors. (Please note that with jQuery 1.6.4, you will need to use bind instead of on to bind the event handler.)

Lastly, I have included the code to restart the slideshow on button click.

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 steps can I take to prevent automatic redirection when submitting an input on an AJAX form in PHP?

I have encountered a strange issue with my HTML post loading dynamically inside a modal popup. I noticed that when I submit the form directly in the post, it works fine but doesn't work inside the modal :/ Every time I try to submit the form from the ...

Tips for preventing harmful messages in a chat room app

As I am working on a chat room website, users are able to input any content they want into the entry field and then send it to all online users. However, I have concerns about security - what if malicious individuals try to inject harmful HTML or JavaScrip ...

Oops! Looks like there was an error: weight is not defined when trying to calculate BMI with the HTMLButtonElement

I'm currently working on a project to create a BMI calculator following specific instructions. I've managed to follow all the guidelines except one regarding the letsCalculateBMI function. The instruction states: letsCalculateBMI should extrac ...

Issue with PHP/MySQL registration page failing to save user information to database

As I work on developing my website that includes user registration and login functionality, I encountered an issue where the registration page was not loading properly. Initially, the registration process worked perfectly, but the next day, upon trying to ...

Struggling to float <aside> to the left of <article> for proper alignment?

tldr; I'm attempting to position the aside-section to the left of the article-section (similar to a sidebar/side column), but my "float" property doesn't seem to be working at all. Is there a way to achieve this without modifying the HTML code an ...

Retrieving the Checkbox Selection from a Grid View and Passing it to the Controller

Within a grid, there is a foreach statement that includes an HTML input checkbox column. The issue at hand is that although the rows and grid populate correctly, the checked checkboxes are not being passed into the controller as part of the Model. Here is ...

What is the best way to create dynamic transparency based on cursor position?

Is there a way to create an animation like the one on https://meetwalter.com, where the transparency changes with the cursor's position? I previously attempted a similar implementation using CSS, but it seems that the website accomplishes this effect ...

Using inline style instead of relying on the quill editor's built-in classes, as classes may not be accessible in order to render HTML effectively

I have integrated the ngx-quill editor into my Angular project as the rich text editor. I plan to save the generated HTML in a database and display it on various browsers using innerHTML. Since the styling is done through a class attribute that references ...

I noticed that my CSS style sheet is only working on three of my pages. What should I do to make sure it affects the fourth page as well?

I am currently facing an issue with my website where I have linked one .css stylesheet to 3 different pages. This is just a temporary template until I finalize the individual look of each page. After performing some div positioning on the site, most pages ...

What is the best way to incorporate JavaScript multiple times on a single webpage?

<script type="text/javascript"> $(function() { var newYear = document.getElementById('HF'); alert('hehe' + newYear); $('#countdown1').countdown({ until: newYear, format: ' ...

Redirecting to new page after submitting form using Ajax

I'm having some trouble with my HTML form submission using JQuery and AJAX. After successfully submitting the form, I want to display a modal and then redirect to another page based on certain conditions. I've written the logic in my JS file wh ...

Determine the length of a string in JavaScript and PHP taking into account "invisible characters" such as and

I have a textarea where users can input text, and I want to show them how many characters they have left as they type using JavaScript or jQuery: var area = 'textarea#zoomcomment'; var c = $(area).val().length; After that, the text is validated ...

Stop bullet points from overlapping when using a floating left image in Internet Explorer 9 and above

Having trouble with bullets displaying in IE9+? Check out this link for more information: I've attempted to fix the issue by creating an ie.css file using conditional comments, but it hasn't worked. Can anyone provide assistance? ...

Auto Height Background Colour in Dual Columns

There seems to be a simple issue that I'm missing here. I have two columns that maintain the same height based on the content inside them, but the background color doesn't fully extend in the shorter column. When the display shrinks, the columns ...

Execute custom time intervals for running jQuery ajax requests

I'm working on a jQuery ajax function that needs to be executed at specific intervals. It should not run on page load, but instead start after 5 minutes and then repeat every 5 minutes thereafter. Below is the code I am using: jQuery(document).ready ...

Create a graph that can retrieve and showcase information stored in a Rails database

Is there a way to incorporate a graph into a Ruby on Rails application that can access and show data from a database file (.rb)? If so, what would be the most optimal approach for achieving this? ...

Wordpress is experiencing a recurring issue with scripts being loaded multiple times

Currently, I am attempting to load some of my scripts from CDNs such as CDNjs and Google. While the scripts are loading correctly, I have noticed a strange issue where each script seems to generate two or even three HTTP requests (for the same script). You ...

Leveraging Vue Data for Storing CSS Properties

I am currently utilizing the Quasar framework in conjunction with Vue for my application development. Below is a snippet of my code: <q-tooltip content-class="bg-amber text-black shadow-4" :offset="[10, 10]"> Save </q-tooltip> <q-tooltip c ...

Is there a bug in Firefox when using the multicolumn columns property with Flexbox?

Could this be a compatibility issue with Firefox? The layout appears fine in Chrome or when I take out columns: 2, then it also displays correctly in Firefox. div { width: 500px; padding: 2rem; display: inline-flex; align-items: baseline; bor ...

Updating votes on the client side in WebForms can be achieved by following these steps

I am currently working on implementing a voting system similar to Stack Overflow's. Each item has a vote button next to it, and I have it functioning server side causing a delay in reloading the data. Here is the current flow: Clicking the vote butt ...