Initiate activity when link is clicked

I am currently in the process of developing a website that includes 5 divs.

<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>
<div class="five"></div>

In one section of the website, I intend to incorporate two hyperlinks.

<a href="">PREVIOUS</a>
<a href="">NEXT</a>

When the "previous link" is selected, I would like it to display the div preceding the current one. The same action should occur when the "next link" is clicked.

Answer №1

Here's an example for you to check out:

JSFIDDLE

Sample HTML :

    <button id="prev" disabled="disabled">Prev</button>
    <button id="next">Next</button>
    <hr />

<div id="main">   
    <div id="div1" class="first current">Div 1</div>
    <div id="div2">Div 2</div>
    <div id="div3" class="last">Div 3</div>    
</div>

JQUERY:

$('#next').click(function() {
        $('.current').removeClass('current').hide()
            .next().show().addClass('current');
        if ($('.current').hasClass('last')) {
           $('#next').prop('disabled', true);
        }
        $('#prev').prop('disabled', false);
    });

    $('#prev').click(function() {
        $('.current').removeClass('current').hide()
            .prev().show().addClass('current');
        if ($('.current').hasClass('first')) {
            $('#prev').prop('disabled', true);
        }
        $('#next').prop('disabled', false);
    });

Answer №2

To improve the structure of your divs, consider assigning them IDs instead of classes. Let's assign a common class to all these divs and add IDs to your links as well:

<div id="one" class="divSlide"></div>
<div id="two" class="divSlide"></div>
<div id="three" class="divSlide"></div>
<div id="four" class="divSlide"></div>
<div id="five" class="divSlide"></div>

<a href="#" id="prevDiv">PREVIOUS</a>
<a href="#" id="nextDiv">NEXT</a>

Next, let's set up click handlers for the buttons:

$("#prevDiv").click(function() {
    var currentDiv = $(".divSlide:visible");

    // Check if there is a previous div
    if (currentDiv.prev(".divSlide").length) {
        currentDiv.prev(".divSlide").show();
        currentDiv.hide();
    }
});

$("#nextDiv").click(function() {
    var currentDiv = $(".divSlide:visible");

    // Check if there is a next div
    if (currentDiv.next(".divSlide").length) {
        currentDiv.next(".divSlide").show();
        currentDiv.hide();
    }
});

Answer №3

Implementing jQuery methods with matching IDs for anchors is a simple task:

var elements = $('.one, .two, .three, .four, .five');

$('#previous, #forward').on('click', function(e) {
    e.preventDefault();
    var newElement = elements.filter(':visible').hide()[this.id]();
        newElement = elements.is(newElement) ? newElement : this.id=='next' ? elements.first() : elements.last();
    newElement.show();
});

FIDDLE

Answer №4

For those utilizing jQuery, it's recommended to explore the functionalities of .next() and .prev()

Answer №5

Another option is to reach the specific element by utilizing jQuery's scrollTo() function.

Answer №6

Using HTML

    <button id="prev" disabled="disabled">Prev</button>
    <button id="next">Next</button>
    <hr /> 

<div id="main">   
    <div id="div1" class="first current">Div 1</div>
    <div id="div2">Div 2</div>
    <div id="div3">Div 3</div>  
    <div id="div2">Div 4</div>
    <div id="div3" class="last">Div 5</div>  
</div>

Incorporate it with JScript

$('#next').click(function() {
    $('.current').removeClass('current').hide()
        .next().show().addClass('current');
    if ($('.current').hasClass('last')) {
        $('#next').attr('disabled', true);
    }
    $('#prev').attr('disabled', null);
});

$('#prev').click(function() {
    $('.current').removeClass('current').hide()
        .prev().show().addClass('current');
    if ($('.current').hasClass('first')) {
        $('#prev').attr('disabled', true);
    }
    $('#next').attr('disabled', null);
});

Style it in your CSS

#div2,#div3,#div4,#div5{
    display:none;
}

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

Is there a way to increase the total of each row by two when a button is clicked?

Looking to enhance the sum of each row by two depending on whether a button is clicked. HTML: <table> <tr> <td> <input type="checkbox" class="prof" name="prof" value="0"> <input class=&quo ...

Can a rotation animation be incorporated into an image in next.js when it is clicked?

Looking to enhance a next.js image with an animation? How about making it rotate 360 degrees upon each click? Despite my attempts at toggling classes, I can't seem to achieve the desired outcome. Any guidance would be greatly appreciated. Thank you in ...

Received an error while attempting to install react-router-dom

I keep encountering this error message whenever I try to install react-router-dom using NPM in VS Code: https://i.sstatic.net/hFshb.png npm ERR! Unexpected end of JSON input while parsing near '...stack-launcher":"^1.0' npm ERR! You can find ...

The utilization of Server.Execute leads to inaccurate HTML rendering exclusively on IE9

Issue - I am encountering a problem with the rendering of a page in different versions of Internet Explorer. The page contains multiple nested div elements, and when calling server.execute within one of the child divs, the output is being displayed incons ...

Prevent sidebar from adjusting size according to text length

Just started exploring Bootstrap 5 and noticed some significant differences from version 4. Check out this jsfiddle for a demonstration of my issue. The problem occurs when the lorem ipsum text exceeds a certain length, causing the sidebar width to be pu ...

Search for data in Mongoose by utilizing a query object that has been obtained from a query string

After extracting and parsing a querystring from a URL, I am able to map it into an object structure like this: { '$and': [ { length: { '$gt': '2' } }, { length: { '$lt': '55555' } } ] } This object is st ...

Loading Data in CodeMirror using XMLHttpRequest (XHR)

Is there any progress in loading the content into CodeMirror using XHR? ...

Access the value within an object that contains an array and compare it with a different array

array1 = [{id: 1, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92e6f7e1e6a3d2e6f7e1e6bcf1fdff">[email protected]</a>', group_ids: ["25"], username: 'test1'}, {id: ...

We encountered an issue loading the resource: the server has returned a 404 (Not Found) error message and a 403 Forbidden error message. However, the resource functions properly on Codepen and localhost

I have a CodePen demo that works fine. However, when I upload it to the server, it stops working properly and most external references show 404 errors. Initially, there were no problems, but now it seems to be an issue like this: !--> http://sachin.ipov ...

Updating dropdown values using another dropdown through AJAX in Node.js: A step-by-step guide

My dilemma involves two dropdown menus: one for selecting the main category and another for choosing a subcategory. The goal is to dynamically populate the subcategory based on the main category selection. In my attempts so far, I have utilized JQUERY and ...

Vue buttons causing table content to vanish

I've encountered an issue with my edit and delete functions where clicking the buttons in the table causes the data to disappear. Below is the full code snippet for reference: <h1>Player Rankings</h1> <!-- More HT ...

Creating a Loopback API that seamlessly integrates with Ember.js

Exploring the use of Loopback to create an API that communicates with Ember. Ember expects JSON data to be enclosed in 'keys', such as for an account: { account: { domain: 'domain.com', subdomain: 'test', title: ...

Is there a way to invoke a high-order function multiple times within the code?

const x = { a:1 }; (function q({a}){ console.log(a); return a; })(x); // unable to execute console.log(q(x)) I'm encountering an issue trying to run line 6. Why is this happening? The console works in line 3 when I remove line 6: Error: q is n ...

What is the best way to deliver data from the main Vue instance to components that are being utilized by vue-router?

Currently, I am utilizing vue-router within a single HTML file instead of using separate file components. I am encountering an issue where I am unsure how to pass the data stored in the Vue data object to the component when loading it for a route. Oddly e ...

Stop files from being downloaded every time the page is visited

Within my Vue.js application, there is an animation that appears on a specific page. However, each time I visit that page, the assets for the animation are re-downloaded from scratch. Although the app does get destroyed when leaving the page, using v-show ...

Error: Attempting to assign a value to property 'x' of an undefined object has resulted in a TypeError

When I tried to create an array of randomly generated circles (stars) in my first code, I encountered a TypeError on this line: stars[i].x = Math.floor(Math.random() * w) Even though stars is defined in the code, the issue persisted. $(document).ready(f ...

Using Angular 4 constructor value in a condition with *ngIf

Within this TypeScript snippet, there is a variable called moreinfo that is initially set to 1. In the constructor, however, the value of moreinfo is changed to 2. Subsequently, based on whether the value is 1 or 2, different div elements are displayed usi ...

What is the best method for updating the .value property within an AngularJS controller?

I managed to successfully pass a value from one AngularJS module to another using the .value method. Here is an example of it working: var app = angular.module('app', []); app.value('movieTitle', 'The Matrix'); var app1 =ang ...

What is the best way to set a checkbox to null instead of false using Angular?

I am currently developing a filtering system that allows users to select different parameters to filter through a list of items. For instance, the item list could be a collection of dishes with filters represented as checkboxes labeled as vegan, vegetaria ...

Utilizing the `this` keyword within a click handler that is passed through an intermediary function

If I initially have a click event handler in jQuery set up like this jQuery('#btn').click(_eventHandler); And handling the event as follows function _eventHandler(e){ jQuery(this).text('Clicked'); } Does the this keyword serve a ...