Toggle the visibility of an element using the onClick() method

I have a unique way of displaying articles on my webpage. Each article is hidden and positioned at the top of the page within different divs, each with a distinct ID. My goal is to allow users to click on a list item and have the corresponding article appear visible on the page. When a new list item is clicked, the previously visible article disappears and the new one appears in its place.

Check out the HTML structure below:

<div class="articlelist">
        <ul>
            <li style="display:block;" onclick="document.getElementByClass('fullarticle').style.visibility='hidden'" onclick="document.getElementById('article1').style.visibility='visible'">ARTICLE 1</li>
            <li style="display:block;" onclick="document.getElementByClass('fullarticle').style.visibility='hidden'" onclick="document.getElementById('article2').style.visibility='visible'">ARTICLE 2</li>
            <li style="display:block;" onclick="document.getElementByClass('fullarticle').style.visibility='hidden'" onclick="document.getElementById('article3').style.visibility='visible'">ARTICLE 3</li>
            <li style="display:block;" onclick="document.getElementByClass('fullarticle').style.visibility='hidden'" onclick="document.getElementById('article4').style.visibility='visible'">ARTICLE 4</li>
        </ul>
    </div>
    <div class="fullarticle" id="article1">
        <h1>ARTICLE 1</h1>
        <p>ABCDEFGH</p>
    </div>
    <div class="fullarticle" id="article2">
        <h1>ARTICLE 2</h1>
        <p>ABCDEFGH</p>
    </div>
    <div class="fullarticle" id="article3">
        <h1>ARTICLE 3</h1>
        <p>ABCDEFGH</p>
    </div>
    <div class="fullarticle" id="article4">
        <h1>ARTICLE 4</h1>
        <p>ABCDEFGH</p>
    </div>

To style these elements, refer to this CSS snippet:

.fullarticle {
  width: 61%;
  margin-right: 2%;
  float: left;
  position: absolute; top: 80px; left: 37%;
  visibility: hidden;
}


.articlelist {
  float: left;
  width: 37%;
}

Answer №1

within the header:

var toggleVisibility = function(item) {
    if(item.style.visibility=='visible'){
        item.style.visibility='hidden';
    } else {
        item.style.visibility='visible';
    }
};

and then modify the onclicks (if you prefer to use them) to

onclick="toggleVisibility(document.getElementById('postID'))"
where postID is the ID of one of the post sections

HOWEVER concealing and revealing content using visibility will cause the lower elements to remain hidden underneath their invisible counterparts, so utilize display with none and block instead

var toggleVisibility = function(item) {
    if(item.style.display=='block'){
        item.style.display='none';
    } else {
        item.style.display='block';
    }
};

This approach may be slightly more intricate, but eliminates the need to include the extensive jQuery library for such a minor task

Answer №2

For those utilizing jQuery, here is a method you can implement:

$('.articlelist ul li').click(function() {
    var i = $(this).index();
    $('.fullarticle').hide();
    $('#article' + (i+1)).show();
});

Check out the Updated Fiddle for demonstration.

Answer №3

If you are using jQuery:

<div class="posts">
<div class="postlist">
    <ul>
        <li style="display:block;" onclick="togglePosts('post1')">POST 1</li>
        <li style="display:block;" onclick="togglePosts('post2')">POST 2</li>
        <li style="display:block;" onclick="togglePosts('post3')">POST 3</li>
        <li style="display:block;" onclick="togglePosts('post4')">POST 4</li>
    </ul>
</div>
<div class="fullpost" id="post1">
    <h1>POST 1</h1>
    <p>ABCDEFGH</p>
</div>
<div class="fullpost" id="post2">
    <h1>POST 2</h1>
    <p>ABCDEFGH</p>
</div>
<div class="fullpost" id="post3">
    <h1>POST 3</h1>
    <p>ABCDEFGH</p>
</div>
<div class="fullpost" id="post4">
    <h1>POST 4</h1>
    <p>ABCDEFGH</p>
</div>
</div>

<script>
function togglePosts(postID) {
    $('#posts .fullPost').hide(); // this hides all currently open posts (if any);
    $('#posts #' + postID).show(); // show post
}
$('#posts .fullPost').hide();
</script>

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

The CSS code I wrote was only targeting one specific page in CodeIgniter, rather than being applied to all

As I work on constructing a basic website utilizing the Codeigniter Framework, I've opted to utilize a responsive HTML5 template. However, I've encountered an issue where the CSS is only being applied to the main URL of the site and not to other ...

How can I create a tickable image grid in Nativescript Angular?

My goal is to create an image grid in a Nativescript Angular App where users can select images and then move to the next page with the selected image IDs or names. I have successfully created the image grid, but I am struggling to make the images tickable ...

What is the best way to align the text next to the initial input and expand the text close to the second input field?

I am an avid user of Bootstrap 4. BC stands as a global pioneer in online news and information, striving to educate, engage, and empower individuals worldwide. - this content should be positioned to the right of the top input field. https://i.sstatic.n ...

JavaScript and CSOM updates cause SharePoint list item properties to disappear

Within my SharePoint environment, there exists a website where users can load a single list item based on their selection using JavaScript and CSOM. This particular list item contains approximately 60 properties defined in its list definition. Users have ...

Guide to bringing API information into a Material UI Card

I've been working on a Recipe app that leverages data from the edamame API. I successfully imported Material UI cards into my .js file to pull data from the API and stored it in a const named recipes. However, I'm facing difficulties in getting t ...

Looking for assistance with customizing my jQuery input styling

Check out this simplified version of the code: $(document).ready(function() { var $checkbox = $('input[type="checkbox"]'); $checkbox.wrap('<div class="stylecheck-container" style="display: inline" />').addClass('style ...

The Flux Router in React Native

I am diving into the world of React Native and currently working on creating a practice app. The issue I'm facing is with the routing functionality in my project. At the moment, I have three main components: the app itself, the router component, and o ...

What is the reason for the lack of automatic refresh in the browser when Component props are changed in App.js and they are used in the state of a class component?

Just getting into learning React and trying to grasp the distinction between props and state. Currently working with two files, App.js and Counter.js. In App.js: import Counter from './Counter' function App() { return ( <Counter initia ...

Make sure to pay attention to the messageCreate event within a direct message channel on discord

I've come across this question repeatedly, and despite trying numerous suggestions, I still can't seem to make it work. Currently, I'm resorting to logging the messageCreate event, but unfortunately, that isn't yielding any results. Any ...

Enhance the functionality of function() by incorporating another function from a different external file

I find myself in a situation where I need to create a web client interface that can interact with different types of hardware. The interface has a core component, and additional features depending on the hardware connected (specifically, the login() proces ...

Having trouble getting Vue.js to cooperate with a brand new Laravel 5.8 setup?

I set up a fresh Laravel project using laravel new sample. Then I executed npm install followed by npm run dev. Next, I modified the welcome.blade.php file as shown below: <!DOCTYPE html> <html> <head> <script type="text/j ...

Revamp the angular design of the mat-tree UI bottom border line issue

Can you help me with changing the direction of the mat tree from right to left? I need to remove the bottom border, please refer to the image https://i.sstatic.net/ecRIO.png here ...

How can I pan/move the camera in Three.js using mouse movement without the need to click?

I am currently working on panning the camera around my scene using the mouse. I have successfully implemented this feature using TrackballControls by click and dragging. function init(){ camera = new THREE.PerspectiveCamera(45,window.innerWidth / windo ...

Utilizing Regex to eliminate consecutive duplicates in a string separated by spaces

My current challenge involves removing only sequential duplicates from a string. For example, in the string "1 2 3 3 2 1", I want to remove one of the consecutive 3's so it becomes "1 2 3 2 1". I thought I had the solution figured out, but when I test ...

What could be the reason behind the failure of JSON.stringify() on this particular array?

I am encountering an issue with an array that I have declared like this: array = []; The array contains values that look like this - .... ChIJOaegwbTHwoARg7zN_9nq5Uc:"ChIJOaegwbTHwoARg7zN_9nq5Uc" ChIJXTwCdefHwoAR9Jr4-le12q4:"ChIJXTwCdefHwoAR9Jr4-le12q4 ...

Using the functionalities of the parent component

Exploring Base.vue <template><div>{{ name }}</div></template> <script> export default { data() { return {name: 'Example Component'}; } }; </script> And introducing Extended.vue: <script> ...

div positioned on top of additional div elements

My HTML code consists of simple div tags <div class="left">Project Name: </div> <div class="right">should have a name</div> <div>Shouldn't this be on a new line?</div> These classes are defined in a stylesheet as ...

Stop the body from scrolling when dialog is open on a mobile screen

I am encountering an issue on a mobile screen where I am displaying a dialog that is longer than the screen size, causing it to scroll. The problem arises when scrolling past the bottom of the dialog (I am utilizing Bootstrap 3) as instead of stopping, it ...

Showcasing a variety of scenarios where resources are being used across several canvases

I am currently working on a project using three.js to develop an interactive web application, but I have hit a roadblock: Within the design, there are numerous canvases enclosed in draggable divs on the page. Each canvas is meant to showcase a 3D object w ...

Validating phone numbers using the REX pattern in either Python or JavaScript

After creating a regular expression, I noticed that it does not accept a certain type of number. https://jsfiddle.net/ofn9knay/1/ Result for 9820098200 false Result for 9820098200#301 false Result for +919820098200 false Result for +91-982-009-8200 false ...