Using jQuery to switch between different content divs

I'm trying to create a script that allows users to toggle between different posts, showing one at a time. However, I'm running into an issue where clicking on a new post doesn't hide the content of the previous one. How can I modify the code so that clicking on a new post hides the content of the previous one and only shows the content of the post that's currently selected? I remember doing something similar a year ago but can't seem to figure it out now.


<script type="text/javascript">
function togglePost(obj) {
          var obj=document.getElementById(obj);
          if (obj.style.display == "block") obj.style.display = "none";
          else if (obj.style.display = "none") obj.style.display = "block";
    else obj.style.display = "none";
}
</script>

<div id="container">
  <div id="sidebar">
    <h3>Posts</h3>
    <p><span onClick="togglePost('q1')">October</span></p>
    <p><span onClick="togglePost('q2')">November</span></p>
    <p><span onClick="togglePost('q3')">December</span></p>
  </div>

  <div id="center">
    <h1> Main Page of post content</h1>
    <p><div id="q1" style="display:none;">October is...testtext testtext testtext</div></p>
<p><div id="q2" style="display:none;">November is...testtext testtext testtext</div></p>
<p><div id="q3" style="display:none;">December is...testtext testtext testtext</div></p>
 </div>
 <br class="clearfloat" />
</div>

Answer â„–1

To hide all elements in your function, simply set their display property to none, then reveal the specific one you need.

function toggleSection(element) {
          var element=document.getElementById(element);
          var isHidden = element.style.display == "none";
          $('[id^=s]').hide();
          if (isHidden) $(element).show();
}

Answer â„–3

Based on your mention of jQuery in the query, I assume it is accessible

function displayPost(id) {
    $('#main-section div').hide();
    $('#' + id).show();
}

Answer â„–4

Try styling your spans in this way:

<p><span class="q1">January</span></p>
<p><span class="q2">February</span></p>
<p><span class="q3">March</span></p>

Update your JavaScript with this code:

$(document).ready(function() {

    // Add onclick event listeners to all span elements in the sidebar
    // Each span's class corresponds to the div it toggles
    $("#sidebar span").click(function() {
        $('#' + $(this).attr("class")).toggle();
    });
});

Check out the live demo here: http://jsfiddle.net/9Nqgs/

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

Target the most recently loaded Vue.js element using jQuery's focus method

Hey there, I am currently utilizing Vue.js to load some data and below is the code snippet: add_line:function() { index = this.lines.length; this.lines.push({id:index}); $('.search_and_select').last().focus(); ...

Why does the JavaScript background color change take precedence over CSS selectors for my object?

Can someone explain why my list elements are not turning blue when I hover over them, even with the CSS and JS provided below? li { background:red; } li:hover { background:blue; } Here is the JS I am using: document.getElementsByTagName("li")[0].style.b ...

Obtain data from various selection lists that share a common identifier

I have three select boxes with the same option IDs but different values. These select boxes will store information in three columns called id, nameuz, nameru. I would like it so that when I select an option from one select box, the other select boxes also ...

Removing a table row on a PHP page (without affecting the database) and ensuring that it does not reappear even after refreshing the page

On one of my pages, I have a script that fetches data from the database and displays it in a table: $statement = $connection->prepare($query); $statement->execute(); $result = $statement->fetchAll(); $data = array(); $filtered_rows = $statement-& ...

What is the reason behind genNewColor function's malfunction?

I'm having trouble with this code that is supposed to generate a random color. The CSS formatting works perfectly, but I suspect there might be an issue with the function itself. When I try to run the code, it doesn't produce any error messages â ...

Tips for retrieving the concealed input value from the div directly preceding

Is it possible for me to retrieve the hidden input value by clicking on the text "upload profile photo"? I don't have much experience in this area. <div> <input type="hidden" value='<?php echo $list['profil ...

Changing between two images using HTML and CSS

I am currently designing a WordPress theme and I would like to create an effect where two different thumbnail images switch on hover. The code that I have come up with so far looks something like this : <a class="thumb" href="posturl"> <img src= ...

What distinctions are there in examining max_input_vars between utilizing ajax and traditional form submission?

HyperText Markup Language <form id="saveform" method="post" action="saveform"> {a plethora of input elements} <input type="submit" value="normal submit"> </form> jQuery var data = $('#saveform').serialize(); $.post('save ...

Is there a way to transition an element from a fixed layout position to an absolute layout position through animation?

I am looking to create a dynamic animation effect for a button within a form. The goal is for the button to move to the center of the form, while simultaneously undergoing a horizontal flip using a scale transform. During the midpoint of this animation, I ...

The gif loader persists even after subscribing

Looking to incorporate the SendGrid subscription widget into my site, but struggling with the implementation. The code provided by SendGrid is partially functional - the loader appears and a success message is displayed upon sign up, but the GIF loader doe ...

Enhancing page accessibility through the implementation of shortcuts

Greetings to all members of the community! I am currently in the process of improving a website by implementing better accessibility practices. I have some concerns regarding a page that displays a large number of repeated result blocks, each containing ...

Displaying logo images specifically designed for mobile devices on a blogger website

I've been working on a blog using a responsive template on Blogger. The logo looks fine when viewed on a computer, but appears blurry on an iPhone. I've tried editing the logo and replacing it with a different one, but the issue remains... You c ...

No elements can be located by Selenium through the use of css, xpath, name, or id in Python

I'm facing a challenge logging into a forum after bypassing the cookie message by switching to its iframe. Despite trying to access elements on the page, I'm encountering difficulties. Here's the code I'm using: #set path, open firefox ...

initiate a click event within another click event

This is an HTML Code snippet: <ul id="linkjess"> <li><a href="javascript:setfolder('medewerkers', '1000');">medewerkers 1000</a></li> <li><a href="javascript:setfolder('medewerkers', ...

Determine the cost for every individual line

I need help figuring out how to calculate the price for each row. Whenever I choose a quantity, it's showing the same price for both rows. Check out my demo here: https://jsfiddle.net/keyro/fw8t3ehs/2/ Thank you in advance! HTML: <table class=" ...

Transform jQuery code to its equivalent in vanilla JavaScript

While I am proficient in using jQuery, my knowledge of pure JavaScript is somewhat limited. Below is the jQuery code that I have been working with: $(document).ready(function() { $.get('http://jsonip.com/', function(r){ var ip_addre ...

Excessive space above and below content while navigating on mobile devices

I'm in the process of creating a new website and I want the navbar to stay fixed at the top when scrolling. The issue is that on mobile devices, there is white space either at the top or bottom when scrolling. The problem arises because I have a side ...

Error message appears when attempting to display a variable in HTML without defining it

Python if($count == 1) { session_register("username"); $_SESSION['username'] = $username; header("location: ../home"); }else { $error = "Your Login Name or Password is invalid"; } CSS -- line 43 <?php echo "<p cl ...

Switch up the color of checkboxes with a dropdown menu option

I have an HTML dropdown code and I am trying to trigger a click event when a specific value is selected. Once this value is clicked, I want some checkboxes to change color. <select> <option value="calculate">calculate</option> ...

How to Trigger a Function in Backbone.js Upon Page Load

My function uses the simple selector $(.some-class) instead of this.$(.some-class). When I call this function in the render, it does not find the .some-class. It seems like the function needs to be called when the DOM is fully loaded. How can I achieve tha ...