Utilize JQuery variables for toggling the visibility of various DIV elements

On my webpage's splash page, there are 4 divs but only the home div is initially visible. The other three are hidden.

Each of these divs has a button associated with it that triggers a jquery click event to swap out the currently visible div for the one selected by the user.

Currently, each button has its own jquery click event hardcoded with the names of the old and new divs to handle the visibility change. This feels redundant and unnecessary.

I am looking to streamline this process by creating a single jquery click-event that dynamically accepts two string variables representing the old div (to hide) and the new div (to show). These variables will be stored in each html button element.

However, I am not sure how to achieve this syntactically.


    <div id="homeDiv">HOME PAGE CONTENT</div>
    <div id="contactDiv">CONTACT CONTENT</div>
    <div id="resumeDiv">RESUME CONTENT</div>
    <div id="portfolioDiv">PORTFOLIO CONTENT</div>

    <script>
        $('#contactButton').click(function() {
            $('#homePage').addClass('blur-out-expand-fwd');
            setTimeout(function() {
                $('#homePage').hide();
                $('#contactPage').show();
                $('#contactPage').addClass('focus-in-contract-bck');
            }, 500);
        });

        $('#contactHomeButton').click(function() {
            $('#contactPage').addClass('blur-out-expand-fwd');
            setTimeout(function() {
                $('#contactPage').hide();
                $('#homePage').show();
                $('#homePage').addClass('focus-in-contract-bck');
            }, 500);
        });
    </script>

Answer №1

After much thought, I came up with a solution:

To streamline the code, I assigned all buttons a class of "navButton" and linked it to the jQuery click event. Each button element now includes attributes for oldDiv and newDiv that are accessed by the click event like so:

CONTACT

$('.navButton').click(function(){

 var oldDiv = "#" + $(this).attr("oldDiv");
 var newDiv = "#" + $(this).attr("newDiv");

$(oldDiv).addClass('blur-out-expand-fwd');
$(oldDiv).removeClass('focus-in-contract-bck');
$(newDiv).removeClass('blur-out-expand-fwd');
$(newDiv).removeClass('focus-in-contract-bck');

setTimeout(function(){

    $(oldDiv).hide();
    $(newDiv).show();
    $(newDiv).addClass('focus-in-contract-bck');

},500  );

});

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

Divergent find function behavior in jQuery when applied to div or tbody

I've encountered an issue while using the jQuery find selector by Id with a div and tbody. Let me simplify my problem for better understanding. HTML <div id='iamdiv'>HELLO</div> <table> <tbody id='iamtbody' ...

Bootstrap: Troubleshooting Margin Problems

I am currently utilizing the Bootstrap sb admin template. I attempted to include 3 columns in a row, but encountered the issue of them being merged together with no space around them. I experimented by modifying the Bootstrap file through a CDN link and pr ...

Is there a specific reason why react-helmet does not automatically update the og meta tag?

I am currently working on generating dynamic og. Specifically, I have a detailed page featuring news on my website. When sharing a link to this page, it should generate the og data. Below is an excerpt of my code: <Helmet> <title>{info &a ...

Update the style dynamically in Angular using an ngFor directive and an array of data

Is there a way to dynamically set the width using data from an array in Angular? The usual approach doesn't seem to work. How can I solve this issue? <div *ngFor="let item of products"> <div [style.width.px]="item.size" class="Holiday"&g ...

The Ajax script is malfunctioning

Currently, I have a program that requires the user to input a city and country. The program then checks the database to see if the city already exists - displaying a warning message using ajax if it does, or adding the city to the database if it doesn&apos ...

Switching between height: 0 and height:auto dynamically with the power of JavaScript and VueJS

Currently, I am changing the height of a container from 0px to auto. Since I do not know the exact final height needed for the container, using max-height could be an option but I prefer this method. The transition from 0 to auto works smoothly, however, ...

Tips for conducting key down event testing on a material ui MenuList element utilizing react-testing-library

Looking to test the key down event on my MenuList component. Component: import MenuItem from '@material-ui/core/MenuItem'; import MenuList from '@material-ui/core/MenuList'; import * as React from 'react'; export default fu ...

Python allows for the retrieval of the aria-label attribute as text based on the div id with the help of libraries like Beautiful Soup

<div id="i19" class="quantumWizTogglePapercheckboxEl appsMaterialWizTogglePapercheckboxCheckbox docssharedWizToggleLabeledControl freebirdThemedCheckbox freebirdThemedCheckboxDarkerDisabled freebirdMaterialWidgetsToggleLabeledCheckbox isC ...

JS unable to insert new row in table

I checked the input value before submitting it in the form and confirmed that it is correct, returning as a string.enter image description here const saveList = () => { const inputListNameText = inputListName.value; fetch('/api/lists' ...

Difficulty in displaying accurate visuals for Albers US Choropleth Map using d3.js and React

I'm currently troubleshooting my code as I'm only seeing a large square of one color when I attempt to create a colorScale for each element with the class "county" on this Albers US map. The desired outcome is something similar to this project: ...

Is it limited to using url routes for clients to communicate with servers in a node.js web application?

Utilizing the Rest API allows the client to interact with the backend through URL routes. When the page loads, the route can be used directly, and ajax requests can be made without reloading the page. Both methods use URL routes to send a request to the se ...

Tap on the div nested within another div

Here is the scenario I am dealing with: <div id="main"> <div id="a"></div> <div id="b"></div> </div> On my website, element B is positioned below element A. How can I attach a click event only to those A elements t ...

Having trouble loading a modal popup on CakePHP 3

Need help! I'm trying to implement a modal pop up when clicking on an edit link, but instead of staying on the same page, it redirects me. I've tried using e.preventDefault() but it's not working. Here's my code: It keeps taking me to h ...

Triggering a JQuery slider event on each individual slider handle within the range

Can events be triggered based on the movement of individual slider handles? I am curious because I need to dynamically update a datepicker depending on which handle is moved. However, I'm unsure if there is a way to: Specify an event for a specifi ...

Error: The value of "$tweetId" cannot be parsed as it is set to "undefined". Please ensure that string values are properly enclosed

I am utilizing sanity, and if you require more details, I will furnish it promptly. When I try to access http://localhost:3000/api/getComments, I encounter the following error message: ClientError: Unable to process value of "$tweetId=undefined". Kindly ...

Cannot POST to /profiles/flash/. GET request is also disallowed for /profiles/flash/

Here I am attempting to incorporate a follow toggle button in a Django template using Django and jQuery AJAX, but encountering an error. Method Not Allowed (POST): /profiles/flash/ Method Not Allowed: /profiles/flash/ I'm unsure where I might be goi ...

Troubleshooting: Absence of Link Style in Lotus Notes 8.5 Email Client

While creating an HTML email and testing it with Litmus, I noticed that Lotus Notes 8.5 is not showing any link styles. Despite using traditional methods to ensure compatibility with older mail clients, the links are still not displaying correctly in Lotus ...

Animated CSS side panel

I'm currently working on creating an animation for a side menu. The animation works perfectly when I open the menu, but the problem arises when I try to animate it back closed. Is there a property that allows the animation to play in reverse when the ...

Invoke jQuery within a nested context once more in the jQuery method sequence

Is it possible to do something like this? jQuery(selector).jQuery(subselector).command(....) Here is the current code snippet: $(' .species') .filter(function () { return !$(this).data('hidden_code_ready'); } .wrapInner('<spa ...

Utilizing Javascript to set the innerHTML as the value of a form

I have written a JavaScript code that utilizes the innerHTML function, as shown below: <script> var x = document.getElementById("gps"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showP ...