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

Invoke the REST API and save the compressed file onto the local machine

This is the code snippet I currently have: jQuery.ajax({ type: "GET", url: "http://localhost:8081/myservicethatcontainsazipfile", contentType:'application/zip', success: function (response) { console.log("Successful ...

AngularJS offers a function known as DataSource for managing data sources

During a recent project, I had to convert xml data to json and parse it for my app. One issue I encountered was related to the DataSource.get() function callback in the controller. After converting the xml data using a service, I stored the converted data ...

Guide on displaying JSON information upon clicking using JavaScript

I'm having difficulty writing the logic for this code. I have extracted data from a vast API. The current code fetches all program titles (some may be repeated) and compares them with an array of late night shows, then displays them once in their own ...

Personalizing the label of a select input using materialui

Working on customizing a select element using the "styled" method: const StyledSelect = styled(Select)` height: 2rem; color: #fff; border-color: #fff; & .${selectClasses.icon} { color: #fff; } & .${outlinedInputClasses.notchedOutl ...

Retrieve data from a JSON file

I have a JSON file containing various player data, and I need to extract the "Name" field from it. { "player": [ { "Position": "TEST", "Name": "TEST", "Squad_No": "TEST", "Club": "TEST", "Age": "TEST" }, ...

Using Python Javascript framework in conjunction with Cherrypy and Mako for dynamic web development

Recently, I started delving into the world of Python and Python web applications. Please excuse my limited knowledge as I am still learning. Currently, I am developing a web application in Python with CherryPy, Mako, and HTML. Now, I have reached the poin ...

Position the div in the center, but for smaller sizes, switch to aligning

My current layout setup is as follows: Left side bar with a width of 200px and positioned at left: 0; Center section with a width of 700px and positioned at left: 250px; Right side bar with a width of 200px and positioned at right: 10px; While this arra ...

Today, I am experimenting with HTML5 File Upload using Capybara and Selenium Webdriver in Ruby

I have encountered a problem with a simple modal that allows users to upload a file using a browse button. Due to some unknown issue, possibly related to the fact that it is an HTML5 file input and the browser adds its own functions to it, testing this has ...

Is there a way for me to programmatically modify a .env file using an npm script?

Currently, I'm managing a project with a .env file that contains confidential information. One of the key elements in this file is 'STATUS'. Just to clarify, this pertains to a Discord bot, The value assigned to the 'STATUS' var ...

Incorporate a course within the conditional statement

Currently, I'm working on the development of an input site and one of my goals is to highlight empty fields. My plan is to check if a field is empty using an if statement and then apply a specific class that will serve this purpose. This is the JavaS ...

Deciding whether an altered image has been successfully loaded

Currently, I am stuck on a minor point while creating a small gallery using jQuery. The code snippet looks like this: <script type="text/javascript> $(document).ready(function(){ $('#thumb1').click(function(){ $('#fullimage ...

The Express app.post endpoint is not acknowledging incoming POST requests from Postman

I am facing an issue where my POST request using Postman to my express app is timing out. Here is the request: And here is the app: import express from 'express' import bodyParser from 'body-parser' import path from 'path' ...

PHP and AJAX combination login page: users may have to sign in twice when accessing on mobile devices

As a novice in the world of programming, I ventured into creating a basic login page - provided below is the simplified version devoid of any security measures. <input type="text" name="username"> <input type="password" name="password"> <in ...

equal child width as parent column container

I'm in the process of developing a custom dropdown search bar that presents results as the user enters text. One issue I'm facing is that the list of results must have a position: absolute. This causes it to disregard the width of the parent col ...

What is the most effective way to access content from a webpage that is rendered

Is there a reliable way to download from links on a JavaScript rendered webpage using Python as the preferred language? I have attempted to use the Selenium Python bindings on a headless server, but it has proven to be slow, error-prone, and unable to acc ...

Tips for creating a smooth scrolling header menu on a standard header

<script> $(document).ready(function(){ $(".nav-menu").click(function(e){ e.preventDefault(); id = $(this).data('id'); $('html, body').animate({ scrollTop: $("#"+id).o ...

Despite receiving a 404 fetch response, the page still exists

I have encountered an issue with my Fetch code (POST) where the response shows status: 404 even though the URL returns a JSON when accessed through the browser. Surprisingly, changing the URL to https://httpbin.org/post brings back normal data. Furthermore ...

Adjust the background color of the arrow in an HTML Select element

My select menu looks different in Firefox compared to Chrome/Edge In Firefox, it displays an "arrow button" https://i.stack.imgur.com/BGFvO.png However, in Chrome/Edge, the arrow button is not present https://i.stack.imgur.com/PXNJn.png Is there a way ...

What is the most efficient method for executing multiple variable=function() and determining when all tasks have been finished?

I am facing the issue of having multiple variables that need to be calculated before being saved as a JSON file. These calculations are done using a function, but when run asynchronously, they end up undefined. After reading about promises, it seems like t ...

Leverage angular-translate to establish placeholder text upon blurring

Just starting out with Angular and facing the challenge of implementing localization in my project. I have a lot of input fields that need their placeholders translated. In my HTML, I'm trying to achieve this: <input type="email" placeholder="{{ & ...