Achieving a stacked arrangement of divs upon click-through using only pure JavaScript

http://jsfiddle.net/Zgxv9/

In the example provided in my fiddle, the div elements return to their original positions when clicked. However, I am looking for a solution where the last clicked div always remains on top. This is my current code:

function displayOne() {
    document.getElementById("fluid1").style.display = 'block';
}

function displayTwo() {
    document.getElementById("fluid2").style.display = 'block';
}

function displayThree() {
    document.getElementById("fluid3").style.display = 'block';
}

If possible, I would like to find a solution without using jQuery. Thank you!

Answer №1

Here is a suggestion to achieve the desired outcome.

You can move the items into a container upon clicking on them, which will maintain their order based on when they were moved into the container.

http://jsfiddle.net/Zgxv9/1/

var target = document.getElementById( "container");

function displayOne() {
    target.appendChild(document.getElementById("fluid1"));
}

function displayTwo() {
    target.appendChild(document.getElementById("fluid2"));;
}

function displayThree() {
    target.appendChild(document.getElementById("fluid3"));
}

If you prefer them to be added to the top, you can use the insertBefore method, and it can be implemented like this: http://jsfiddle.net/Zgxv9/7/

var target = document.getElementById( "container");

function displayOne() {
    target.insertBefore(document.getElementById("fluid1"), target.firstChild);
}

function displayTwo() {
    target.insertBefore(document.getElementById("fluid2"), target.firstChild);;
}

function displayThree() {
    target.insertBefore(document.getElementById("fluid3"), target.firstChild);
}

Answer №2

EXAMPLEhttp://jsfiddle.net/KsJz8/2/

var box = document.getElementById('box');

function showBox() {
    var popup = document.getElementById("popup");
    popup.style.display = 'block';
    box.insertBefore(popup, box.firstChild);
}

Answer №3

To utilize the insertBefore technique, you can refer to the documentation. A live example is available for demonstration.

function showContent(evt) {
    evt.preventDefault();
    var identifier = this.href.split('#')[1],
        content = document.getElementById('fluid' + identifier),
        allContents = document.getElementsByClassName('container-fluid');

    //if current content is not the first one, insert it before the initial content
    content !== allContents[0] && content.parentNode.insertBefore(content, allContents[0]); 
    content.style.display = 'block'; //then display it
}

[].forEach.call(document.getElementsByClassName('toggle'), function(element){
    element.addEventListener('click', showContent);
});

Answer №4

Enhancing the modularity of the function is essential. Here is the updated code: http://jsfiddle.net/a3RtP/12/

function modifyElement(elementID) {
var element = document.getElementById(elementID);
element.style.display = 'block';

var clonedElement = element.cloneNode(true);
// console.log(clonedElement);

var parent = element.parentNode;
// console.log(parent);

var containerList = document.getElementsByClassName("container-fluid");

var firstElement = containerList[0];

parent.insertBefore(clonedElement, firstElement);
parent.removeChild(element);
}

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

What steps do I need to take to adjust this function based on the timezone?

Is there a way to retrieve the current time based on a specific timezone of my choice? let getCurrentTime = () => { var today = new Date(); var hh = String(today.getHours()) var mm = String(today.getMinutes()) //January is 0! var ss = ...

Setting the response type to text in Angular 6 when making an http call

Attempting to send an HTTP request to the Spring REST API, which returns a string value ('success' or 'fail'). However, I am uncertain of how to specify the response type as a string value when making the call to the API. The error mess ...

Tips for selecting a checkbox with Puppeteer

I've implemented the code in this way: await page.$eval('input[name=name_check]', check => { check.checked = true; }); This code is intended for multiple checkboxes. However, I need it to work for a single checkbox only. Is there a way ...

JQuery Mobile Listview Filter Not Working: Troubleshooting Tips

Recently diving into the world of jquery mobile, I've managed to successfully create a homepage and a sub-page labeled "bible_studies," complete with a dynamic list generated through AJAX. Everything seems to be functioning perfectly except for one i ...

Retrieving complete database in JSON format with the help of the mysql node.js driver

Currently, I am working on developing a JavaScript file to extract a JSON dump from an entire MySQL database that is running on the server side. I have successfully found and implemented the MySQL driver for node.js for executing queries. While the process ...

Fixing content at the bottom inside a container with Bootstrap 4

My app is contained within a <div class="container">. Inside this container, I have an editor and some buttons that I always want to be displayed at the bottom of the screen. Here's how it looks: <div class="container> // content here.. ...

How do I view a wildcard in my ID selector using jQuery?

When I want to initially hide various content scattered around the page, I usually use the following jQuery code: $('#objective_details, #time_estimate_details, #team_members_details, #resources_details').hide(); Is there a method to utilize a ...

What is the best way to adjust the spacing between posts on a website

https://i.stack.imgur.com/VderY.jpg Looking at the image, there are 3 posts lined up in a row. I'm trying to adjust the spacing between each item to be about 20%. Specifically, I want the distance highlighted by the red dashes, instead of the current ...

Video from Brightcove continues to play even after closing the modal dialog

My concept for opening a Brightcove video in a modal dialog when a button is clicked has been successfully implemented. Below is the code snippet I used for this implementation: Html code: <a class="videoTutorialB" href="#">Watc ...

Displaying the number of tasks completed compared to the total number of tasks within a JavaScript ToDo list

Currently, I'm in the process of creating a basic ToDo list using HTML, JS, and CSS. The last task on my list is to display to the user the total number of tasks and how many have been completed. For instance, if there are 3 completed tasks out of 7 i ...

Is it possible for an HTML file to not recognize an external CSS stylesheet?

I've been trying everything, but I can't seem to get these two documents to work together. I'm confident that the CSS file is linked correctly with the right file name. I decided to give it a shot after watching this coding blog tutorial on ...

Resolving conflicting event handlers within vue.js

I have a situation where I'm trying to use two buttons on a page to navigate to different sections. When I include only one button, everything works fine. But when I include both buttons, only one of them functions properly. Upon debugging, I noticed ...

Update the style class of an <img> element using AJAX

My success with AJAX enables PHP execution upon image click. However, I seek a real-time visual representation without page reload. Thus, I aim to alter <img> tag classes on click. Presently, my image tag resembles something like <img title="< ...

Steps for initializing a Vue component instance by passing parameters

Being a novice in the realm of Vue, I am eager to gain knowledge on how to effectively create and reuse Vue components. However, I am encountering an issue where the initial data passed to a component does not update upon a click event. Shown below is a ...

Setting the $dirty flag to true when a value is entered in the text box, but not the other way around

When I enter a value in the text box, myForm.$dirty gets set to true. However, the flag does not revert back to false when I delete all values from the text box. Why is this happening and how can I fix it? <input name="input" ng-model="myModel.text"& ...

Error: An unexpected identifier was found within the public players code, causing a SyntaxError

As a newcomer to jasmine and test cases, I am endeavoring to create test cases for my JavaScript code in fiddle. However, I'm encountering an error: Uncaught SyntaxError: Unexpected identifier Could you guide me on how to rectify this issue? Below is ...

"Counting the clicks on the filter button in React

I have: var RightPanel = React.createClass({ componentDidMount: function () { this.load(); }, load: function(){ }, render: function () { return ( <div> <div className="row"> ...

Issue with Abide Validation Events not triggering in Reveal Modal for Foundation Form

Currently, I am developing a login/registration feature for a basic web application using Foundation. On the index page, users are presented with a login screen and a register button. When the user clicks on the register button, a Reveal Modal pops up cont ...

Three.js: dividing the camera's view frustum (similar to what is done in Cascade Shadow Mapping)

Discovering the intriguing world of Cascade Shadow Mapping has been quite insightful (check out this helpful tutorial I stumbled upon: link). I'm currently exploring how to implement a similar approach in Three.js, with the added advantage of having t ...

Is there a way to change the background color of the body on click and have it applied throughout the entire site

Is there a way to change the background-color of the entire site and specific modal elements when a user switches between two radio buttons? Here is the HTML code for the radio buttons: <div class="btn-group btn-group-xs" data-toggle="buttons"> ...