Leveraging the power of JavaScript to reveal concealed div elements

I've got a collection of divs (five in total) with a hidden class applied to them in my CSS stylesheet. Each div also has its own unique ID. My goal is to use JavaScript to reveal these divs one by one.

Here's an example of what I'm looking for:

<style>
.hidden{
     display:none; }
</style>
<script>
function displayDiv1(){
    document.getElementById('div1').style.display = "block"; }
function displayDiv2(){
    document.getElementById('div2').style.display = "block"; }
</script>
<div class="hidden" id="div1">
<p>some stuff here</p>
</div>
<div class="hidden" id="div2">
<p>some more stuff here</p>
</div>

Check out this non-functional jsfiddle http://jsfiddle.net/DAzZT/

Is it feasible to achieve this functionality, or do I have to specify each individual div as hidden by using the ID rather than the class?

Answer №1

The issue lies with using the getElementById function directly, instead you should use document.getElementById. It is recommended to consolidate this functionality into a single function for efficiency:

function displayElement(id) {
    document.getElementById(id).style.display = "block";
    return false;
}

To utilize this function, simply call it like so:

<a href="#" onclick="return displayElement('target_element_id');">Display Element</a>

Answer №2

One way to achieve this is by utilizing jQuery. By initially setting the display property in your CSS to none, you can then use jQuery functions such as $('#element').show(); to make the element visible or $('#element').hide() to hide it again.

Answer №3

give this a shot sandbox

make sure to invoke it with the document object

function showDiv1(){
document.getElementById('box1').style.display = "block";
}
function showDiv2(){
 document.getElementById('box2').style.display = "block"; 
}

Answer №4

element, ensure that your functions are placed in the appropriate scope as demonstrated in your inquiry. Utilize the document.getElementById method to access elements on the page. Adjust the onLoad setting to 'no wrap(body)' on the left side.

Answer №5

Initially, there is a mistake in the code provided. It should be noted that the correct syntax is document.getElementById rather than getElementById.

Another error present in the fiddle is wrapping the code within an onLoad function. This leads to the JavaScript code appearing as follows:

window.addEvent('load', function() {
    function display1(){
        document.getElementById('div1').style.display = "block";
    }
    function display2(){
        document.getElementById('div2').style.display = "block"; 
    }
});

The function definitions are contained within a function, causing them to be inaccessible in the global scope. Clicking on any links will result in a Uncaught ReferenceError.

To resolve this issue, you have two options: either deselect the wrap option (select no wrap (head) or no wrap (body) from the first dropdown menu under choose framework) or add the functions to the global window object while maintaining the onLoad wrapper and adjusting your code like so:

window.display1 = function(){
    document.getElementById('div1').style.display = "block";
}
window.display2 = funnction(){
    document.getElementById('div2').style.display = "block"; 
}

Answer №6

Consider using document.getElementById in place of getElementById when working with JavaScript functions.

Answer №7

Here's an easy fix :

<script>
    function showDiv(number){
       document.getElementById('element'+number).style.display = "block";
       return false;
    }
</script>
<a href="#" onclick="return showDiv(1);">Show Element 1</a><br />
<a href="#" onclick="return showDiv(2);">Show Element 2</a>

See demonstration here (I made changes to the CSS for better visibility of both 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

Encountered a SyntaxError: Unexpected token "e" while attempting to parse a JSON string

When I attempt to use JSON.parse in order to convert the string below into a JavaScript object, I encounter an "Uncaught SyntaxError: Unexpected token e" error. { "__type": "HRIS.oHRData, HRIES, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", ...

Using ESP8266 as a client and setting up an AJAX web server

My goal is to use ESP8266 as a client that will be controlled by a server running on my computer. I want the server to send commands to the ESP8266 using AJAX, and for the ESP8266 to respond to these commands and also be able to send data back to the ser ...

What is the best way to customize the appearance of Image tags located inside SVGs, whether they are in separate files or embedded within the code

I am developing a custom SVG editor application and facing an issue with implementing a highlighted effect when an <image> element is clicked. I have successfully accomplished this for other elements like <circle> by adjusting attributes such a ...

Discover the Color's Value in Relation to a Different Color

When it comes to my CSS, I like to use .scss to make as many variables as possible. It's easy to create a variable for one color, like $primary-color. From there, I want to work with different shades of that color, which I can easily pinpoint using Ph ...

Tips for utilizing the Python class method decorator for implementing GETTER and SETTER functions

I am currently diving into the world of GETTER and SETTER properties in Python class methods, but I'm struggling to grasp how to implement them effectively. Here is a snippet of my code - can you help me with the following: Can you review if I am u ...

Why opt for ref.current over directly applying the condition?

I'm curious as to why the code uses if (ref.current && !ref.current.contains(event.target)) rather than if (!ref.current.contains(event.target) function useOutsideAlerter(ref) { useEffect(() => { // Function for click event function hand ...

Utilizing Node.js with Redis for organizing data efficiently

Currently, I am in the process of configuring a Redis cache system for storing incoming JSON data in a specific format. My goal is to create an ordered list structure to accommodate the large volume of data that will be stored before eventual deletion. Th ...

Is there a way to render a component without having to render AppComponent constantly?

I am looking to display two components (AppComponent and UserComponent) without constantly displaying AppComponent. Here's how my code is structured: app.routing.module.ts const routes: Routes = [ { path: '', component: AppComponent ...

In Node.js, when accessing a Firebase snapshot, it may return a

Currently, I am utilizing Firebase functions to execute the code for my Flutter application. This code is responsible for sending push notifications to my app. However, I am encountering an issue where I receive a null value at snap.val(). Take a look at h ...

Sorting alphanumeric strings in React Bootstrap Table Next on a dynamic table

I am facing an issue with sorting columns in a dynamic table with over 70 columns using React-Bootstrap-Table-Next. The problem arises when trying to sort the columns in alphanumerical order, as some columns contain numbers and others contain letters. The ...

What is the correct way to implement checkbox validations using jQuery?

I have a total of 3 checkboxes that I would like to arrange in a particular order based on their checks. Currently, when one checkbox is selected for download, the logic I have implemented only considers the first checkbox and ignores the rest. I am look ...

JavaScript decimal validation not functioning as intended

Hey everyone! I've created a script that restricts textboxes to allow only decimal numbers. Take a look at the code snippet below: function onlyDecimal(evt) { if (!(evt.keyCode == 46 || (evt.keyCode >= 48 && evt.keyCode <= 57))) ...

What is the process for implementing npm packages in Laravel after they have been successfully installed?

After installing npm packages in Laravel, how do I require them? For example, let's say I need the package sweetalert2. To install it, run the command: npm install --save sweetalert2 Now, do I need to include it in the \resources\assets ...

Ways to eliminate the final empty space in a grid

Looking to create a layout with 5 boxes? Currently, I have managed to set up the grid structure, but the issue is that there is still some space below the last item in the grid. Below is the styled component for Container: const Container = styled('di ...

Mongoose and MongoDB in Node.js fail to deliver results for Geospatial Box query

I am struggling to execute a Geo Box query using Mongoose and not getting any results. Here is a simplified test case I have put together: var mongoose = require('mongoose'); // Schema definition var locationSchema = mongoose.Schema({ useri ...

What is the method for incorporating an async middleware into a router route?

I am currently setting up routes for an express router in my project. I have a validator that deals with promises, requiring me to use await in the code. Here is how it looks: constructor() { this.router = express.Router(); this.router.use(express. ...

Panel that collapses and increments its ID each time within my loop

I have a Collapsible Panel with this header, <div id="CollapsiblePanel1" class="CollapsiblePanel"> <div class="CollapsiblePanelTab" tabindex="0">Comments</div> <div class="CollapsiblePanelContent"> Content &l ...

displaying a post-end issue on the express server

Currently, I am working on a school project that requires the development of a client-server application. The specific task is to create a webshop that can load products using AJAX. To achieve this, I am utilizing jquery and the $.load() method. Within my ...

Selenium for handling multiple input fields

Having some trouble figuring out how to input values for selecting a building. Initially, there are two empty input fields for selecting a building. As you enter one, it should add an additional empty input field. I'm struggling with the indexing and ...

What is the best way to position a static element next to a Vue draggable list?

I'm currently working on implementing a feature to display a list of draggable elements using vue-draggable. These elements are occasionally separated by a fixed element at specified position(s). My approach so far has involved creating a separate el ...