How to toggle between displaying divs using JavaScript and Jquery

How can I use JavaScript to show or hide specific divs on page load and upon clicking different links?

I want to display the "houseImages" div by default, while hiding the "landImages", "renovationImages", "UpcomingImages", and "voteForNext" divs. Then, when the user clicks on "Landscaping", I want to show the "landImages" div and hide the "houseImages" div. This functionality should continue through the list of links, so that when the user clicks on "Painting", the "houseImages" div reappears. How would I achieve this with JavaScript?

Here is my current code:

<Div id="mainContent">
            <h2> Our House </h2>
            <div id="columnLeft">
                <ul>
                    <li id="leftColumnPainting">
                        <a href="#houseImages">Painting</a>
                    </li>
                    <li id="leftColumnLandscaping">
                        <a href="landscaping.html">Landscaping</a>
                    </li>
                    <li id="leftColumnRenovations">
                        <a href="renovations.html">Renovations</a>
                    </li>
                    <li id="leftColumnUpcoming">
                        <a href="upcoming.html">Upcoming</a>
                    </li>
                    <li id="leftColumnNext">
                        <a href="whatsnext.html">Vote for <br>Next!</br></a>
                    </li>
                </ul>
            </div>
            <div id="columnRight">
                <div id="title">
                <p> Over the course of a couple years we have done a number of projects around the house. Click on a link to your left to see the improvements! Don't forget to vote for what's next!
                </p>
                </div>
                <div id="houseImages">
                <ul>
                    <li>
                        <a href="Painting.html"><img src="./img/house1.jpg" /></a>
                    </li>
                    <li>
                        <a href="Painting.html"><img src="./img/house2.jpg" /></a>
                    </li>
                    <li>
                        <a href="Painting.html"><img src="./img/house3.jpg" /></a>
                    </li>
                    <li>
                        <a href="Painting.html"><img src="./img/house4.jpg" /></a>
                    </li>

                </ul>
                </div>
                <div id="landImages">
                <ul>
                    <li>
                        <a href="Painting.html"><img src="./img/land1.jpg" /></a>
                    </li>
                    <li>
                        <a href="Painting.html"><img src="./img/land2.jpg" /></a>
                    </li>
                    <li>
                        <a href="Painting.html"><img src="./img/land3.jpg" /></a>
                    </li>
                    <li>
                        <a href="Painting.html"><img src="./img/land4.jpg" /></a>
                    </li>

                </ul>
                </div>
                <div id="renovationImages">
                <ul>
                    <li>
                        <a href="Painting.html"><img src="./img/renovation1.jpg" /></a>
                    </li>
                    <li>
                        <a href="Painting.ht... etc

Answer №1

To improve your website's functionality, consider updating the <a href=""> to refer to the targeted div ID. You could implement a solution such as:


$("#navmenu li a").click(function(event) {
   event.preventDefault();
   $("contentarea div").hide();
   $("#"+$(this).attr("href")).show();
});

Answer №2

My preference lies with the Hide -> fadeIn effect pairing. When working with 2 buttons and 2 divs, you can toggle which one is displayed using this method:

HTML:

<div id="a">div 1</div>

<div id="b">div 2</div>
<button id="c">show div 1</button>
<button id="d">show div 2</button>​

CSS:

div{
    width: 200px;
    height: 200px;
    border: solid 1px;
    display: none;
}​

JS:

$('#c').click(function() {
    $('#b').hide();
    $('#a').fadeIn();
});
$('#d').click(function() {
    $('#a').hide();
    $('#b').fadeIn();
});​

Check out the JSfiddle example: http://jsfiddle.net/HSNLN/

This method can be applied to any jQuery-triggered event to show/hide different div elements.

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

Having trouble with your jQuery AJAX function not receiving the text returned from your PHP file?

After extensive searching, I have come across several individuals facing the same issue as me, but unfortunately, none of them seem to have found a solution. The problem at hand is that PHP is not providing any data to the AJAX function. When I try to dis ...

"Positioning a div around a Bootstrap form-inline: A step-by-step guide

When using Bootstrap 3 "form-inline" within a <div>, I noticed that the div seems to be nested within the form-inline. This is how my code looks: HTML <div class="wrapper"> <div class="form-inline"> <div ...

What causes the findByIDAndUpdate method to return a `null` value in Mongoose 6?

I am working with nodejs v18, Express v4, and Mongoose v6. I am attempting to update a document, but when using the line below, it returns null. const doc = await User.findByIdAndUpdate(userId, newUser, { new: true }) // doc is null The object newUser con ...

What is the method for accessing a JQuery mapping array in PHP?

I am attempting to transfer data from JQuery to PHP and then save it in the database. Here is my JQuery code snippet: var map = $.map(customFieldIds, function(value) { return { name: value, value: customFieldValues[value] ...

Enable hyperlink to open in a new browser tab after user clicks on button embedded inside an iFrame

<head> </head> <div> <iframe src="https://....."></iframe> </div> I'm looking for a way to open the link in a new tab when clicking on this button. Currently, the page loads within the iFrame when clicked. I&a ...

Is it considered poor form for an Angular controller to invoke a function on a directive?

My custom Angular directive functions as a unique combobox, where clicking on the input control reveals a div below it with a list of items from a model object. The user can type text into the input control to filter the displayed list. In addition to the ...

Ways to resolve the angular error "Encountering an unhandled exception: Unable to locate module 'typescript' "?

I'm encountering errors when running ng serve. I've attempted the following code as well, but I'm still facing the same error: npm install -g typescript Error displayed in text format D:\xampp\htdocs\angular\axen>ng ...

The withRouter function in React Router does not automatically inject the router

Desiring to implement withRouter on my primary React component named 'App'. You can view the documentation here. This is how I utilize it: import React from "react"; import { render } from "react-dom"; import {Router, Link, hashHistory, Rout ...

jQuery for Implementing Pagination Across Multiple Tables

As a novice in the world of JavaScript and jQuery, I am struggling with implementing pagination for multiple tables on a single page. My goal is to have several tables that can be paginated using one navigation system. However, all my attempts so far have ...

Mobile video created with Adobe Animate

Currently, I am designing an HTML5 banner in Adobe Animate that includes a video element. However, due to restrictions on iPhone and iPad devices, the video cannot autoplay. As a workaround, I would like to display a static image instead. Can anyone provid ...

Is it feasible to utilize math.max with an array of objects?

When it comes to finding the largest number in an array, solutions like this are commonly used: var arr = [1, 2, 3]; var max = Math.max(...arr); But how can we achieve a similar result for an array of objects, each containing a 'number' field? ...

The ForEach function does not execute actions on every individual object, but rather only once

I am currently developing a Deck building application for a card game. In addition, I have set up a database to manage the cards that I sell and play with. The deck builder tool I created allows me to deplete the stock of sellable cards when adding them to ...

Send a request from my own local client without encountering any Cross-Origin Resource Sharing (C

I am attempting to send a request from my locally hosted Node.js/Express.js client to a third-party API that I have deployed on the cloud. Strangely, I keep running into a CORS error whenever I make the request. The interesting part is that the request wor ...

Button triggered page refresh after Ajax content load

After using AJAX to load a page into a div, everything seems to be working as expected. However, I'm encountering an issue where clicking on buttons within the loaded content causes the entire page to refresh unexpectedly. This behavior is inconsisten ...

Arrange the list by first names in the array using Ionic 3

What is the process for arranging a list by firstName from an array? This is my code in my.ts file: initializeItems(){ this.items = [ { avatar: '../../assets/imgs/profile1.jpg', firstName:'Sterlian', lastName:'Victorian ...

Trouble concealing tab using slideUp function in Jquery

Whenever I click on the 'a' tag, it displays additional HTML content (list) that is controlled by generic JS code for tabs. However, I want to hide the list when I click on the "Title" link again. What can I do to achieve this? You can view a de ...

Utilize CSS to exclusively filter through items

Is it possible to use CSS alone to filter a list of items based on specific links being clicked? I have a list that should display only certain items when corresponding links are clicked. HTML: <!-- Header links --> <a href="#" class="all" tabin ...

No matter how much I try, the text refuses to align with the top-left corner

I have been working on creating a loading screen, but I am facing an issue with aligning the h1 tag selected to the top left. As a young developer at the age of 13, I am quite confused. I attempted to use the following CSS properties: vertical-align: top; ...

The dropdown menu is malfunctioning when accessed within the mobile view of a jQuery

Take a look at this code snippet on Fiddle: https://jsfiddle.net/rizwanali98601/ngofhc24/12/. The table below contains a dropdown inside a jQuery Datatable. When the button is clicked, an option is supposed to be added to the dropdown. However, in mobile ...

I encountered an issue while attempting to connect to my MySQL database using my Express API endpoint: error message "connect ECONNREFUSED 127.0

I am currently in the process of developing a web application for a bootcamp using Express and MySQL. I have set up a route to handle a GET request to an endpoint which is supposed to query my MySQL database table and retrieve all records. My intention is ...