Combining CSS and JavaScript to handle two events with a single onClick

Here is the code I've created:

<a href="#" id="home" class="showLink" onclick="showHide('example');return false;">
    <li class="buttons">home</li>
</a>
<a href="#" id="user" class="showLink" onclick="showHide('example2');return false;">
    <li class="buttons">users</li>
</a>

This is the JavaScript code:

function showHide(shID) {
   if (document.getElementById(shID)) {
      if ((document.getElementById(shID).style.display == 'none')||(document.getElementById(shID).style.display == '')) {
         document.getElementById(shID).style.display = 'block';
      }
      else {
         document.getElementById(shID).style.display = 'none';
      }
   }
}

I am looking to have the 'example' appear and 'example2' hidden when clicking on 'home', and vice versa. Is this achievable?

Answer №1

For a straightforward approach, you can utilize the function provided below:

function toggleVisibility(targetID) {
    // hide all specified elements
    var elementIDs = ["section1", "section2"];
    for (var i = 0; i < elementIDs.length; i++) {
        document.getElementById(elementIDs[i]).style.display = 'none';
    }
    // display the one passed as an argument
    document.getElementById(targetID).style.display = 'block';
}

View a live example on jsFiddle here.

Answer №2

To achieve the desired functionality of showing and hiding elements based on unique IDs, you can implement the following code snippet:

function toggleElements(elementID) {
   var id = $(elementID).attr("id");
   if(id == "toggle-element1") {
       $(element1).show(1000);
       $(element2).hide(1000);
   } else if(id == "toggle-element2") {
       $(element2).show(1000);
       $(element1).hide(1000);
   }
}

The provided code utilizes jQuery for toggling elements based on their unique IDs.

Answer №3

Utilizing only Vanilla JavaScript:

http://jsfiddle.net/9GQX2/1/

<script>
function toggleContent(shID) {
if(shID=="section1")
{
shID2="section2";
}
else
{
shID2="section1";
}
if (document.getElementById(shID)) {
  if ((document.getElementById(shID).style.display == 'none')||(document.getElementById(shID).style.display == '')) {
     document.getElementById(shID).style.display = 'block';
     document.getElementById(shID2).style.display = 'none';
  }
  else {
     document.getElementById(shID).style.display = 'none';
  }
  }
}
</script>

Answer №4

Check out this code snippet using jQuery:

Here's the HTML code:

 <a href="#" id="home" class="showLink" onclick="showHide(this);return false;"><li class="buttons">
        home
        </li></a>
        <a href="#" id="user" class="showLink" onclick="showHide(this);return false;"><li class="buttons">
        users
        </li></a>

And here's the JavaScript function:

function showHide(ele) {
   if($(this).attr('id') == 'home'){
      $('#example').show();
      $('#example2').hide();
    }
    else{
       $('#example').hide();
       $('#example2').show();
     }
}

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

Overflow leads to the entire page scrolling

My goal is to design a webpage that remains static without any scrolling. Some specific elements within the page may be allowed to scroll independently, but I am focused on preventing the entire page from scrolling. The main issue arises when a deeply nest ...

Query to retrieve the most recent message from all users and a specific user resulting in an empty array

My goal is to retrieve all messages exchanged between User A and any other user. This is my schema structure: const MostRecentMessageSchema = new Schema({ to: { type: mongoose.Schema.Types.ObjectId, ref: "user" }, from: { type: mongoose ...

How can I assign a URL when a button is clicked in Next.js?

Can I manipulate queryString values using nextjs and reactjs? I have a filter list on my page that changes the displayed results when clicked. I want to update the URL's queryString values so that if a user navigates away from the page and then retu ...

pattern to eliminate particular anchor elements

I am facing a challenge with a large HTML file that contains approximately 300 similar anchor tags that need to be removed: <a href="javascript:void(0);" onclick="javascript:thumbs(198, 0, 'architecture')" class="icon"></a> The prob ...

Safari shows a contrasting outcome

Having an issue with compatibility in the safari browser You can check out the site here: The problem lies with the text inside the image, I want it to display properly like it does in Chrome. Here is the desired result for Safari as well. Below is the ...

Unable to retrieve push token for the device. Please verify the validity of your FCM configuration

Looking for a solution to the issue of obtaining a push token Error: Unable to retrieve push token for device. Ensure that your FCM configuration is correct I have integrated Expo permissions and notifications in my React Native app, but nothing seems to ...

Creating a javascript function to update content on click

Recently, I've been designing a webpage and encountered an issue. I want the text in a specific area to change whenever a user clicks on a link. Below is the code snippet related to the section I want to modify using a JavaScript function. <div id ...

Utilizing web components from NPM packages in conjunction with Svelte

My current project involves the development of a simple Single Page App (SPA) using Svelte. I have successfully implemented a basic layout and styling, as well as an asynchronous web request triggered by a button click. Now, my next objective is to utiliz ...

Capturing HTML form values and storing them in my JavaScript data object

I have a JS object with preset data as shown below in the variable var json. I am trying to create a simple HTML web form where I want the user inputs to be added as a new data set within my initial JS object. Here is the initial JS object data. The submi ...

Utilizing sessions in Node.js Express3 to verify user's authentication status

Here is the content of my app.js file: app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.enable('jsonp callback'); app.set('view engine&apo ...

Locate and modify a specific element within an array of objects

Currently, I am working with an array that looks like this: arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}]. However, I need to add a condition to the array. If ...

The presence of whitespace is causing disruptions in the text alignment within div elements

I've noticed some unwanted white space on my website when viewing it in Chrome and Internet Explorer. It's interrupting the flow of text and I can't figure out where it's coming from. Can someone help me locate and remove this pesky wh ...

What's the best way to retrieve a value from a function that invokes itself multiple times?

My task involves navigating through nested object data to find a specific result. I am using the findByKey function, which recursively calls itself until the desired result is found. However, instead of returning object.source, I am getting undefined. as ...

Is it better to append content in JQuery rather than replacing it with .innerHTML?

Here is a function designed to retrieve older wallposts from a user, 16 at a time, and add each chunk of 16 to the end of the current list in the div called "sw1". The function works well, except when there is a wallpost containing a video or embedded obj ...

How can I extract the domain name using a regular expression in JavaScript?

I am struggling with creating a regular expression to extract the main domain name from a URL. The URLs I have are: http://domain.com/return/java.php?hello.asp http://www.domain.com/return/java.php?hello.asp http://blog.domain.net/return/java.php?hello.as ...

menu fails to expand when clicked in mobile view

Could someone please help me troubleshoot why the menu icon is not expanding in mobile view? I'm not sure what I did wrong. Here is the link for reference: Snippet of HTML: <nav class="navbar navbar-default navbar-fixed-top" role="navigation"> ...

Tips for showcasing content on a jQuery calendar

I have a jQuery calendar implemented on my website and I would like to show a list of local holidays on the calendar. The calendar is functioning correctly with the script below, but I just need help displaying the holidays. <script> $(document).r ...

Mongoose Alert: Unable to Create Schema Instance

Below is the Schema file that I'm using: const mongoose = require("mongoose"); const ProblemSchema = new mongoose.Schema( { slug: { type: String, required: true, unique: true, }, title: { type: String, ...

Make sure to deselect all other radio buttons when selecting one, running into difficulties

Having an issue with my UI when selecting radio buttons by clicking on a div: A loop that displays different radio buttons: {% for product in collections.regalos.products %} <li class="grid__item large--one-third gift-card"> <div class="gift-s ...

What could be causing Jest to prevent me from using the node testing environment, especially when they have made changes to it?

I am currently working on testing a React component within Next.js using Jest. Jest made an official announcement regarding the change of default test environment to Node: Due to this update, the default test environment has been switched from "jsd ...