Original state of class name is restored upon change

I'm currently working on creating a Lightbox-style effect using CSS and Javascript. The idea is to change the classname of an element (OverlayContainer) to toggle between a normal background and a darker overlay. However, I've run into an issue where the state changes briefly upon clicking the submit button, but then immediately reverts back to its original state (OverlayInactive). If anyone has any insights or suggestions on why this might be happening, I would greatly appreciate it.

Below is the CSS code:

.OverlayBoxInactive {
    background-color: rgba(0, 0, 0, 0);

    position: absolute;
    width: 0%;
    height: 0%;

    top: 0px;
    left: 0px;
}

.OverlayBoxActive {
    background-color: rgba(0, 0, 0, 0.85);

    position: absolute;
    width: 100%;
    height: 100%;

    top: 0px;
    left: 0px;
}

And here is the corresponding Javascript code:

function ActivateOverlay() {

    var overlayBox = document.getElementById("OverlayContainer");
    var elementClassName = overlayBox.className;

    if (elementClassName == "OverlayBoxInactive") {
        overlayBox.setAttribute("class", "OverlayBoxActive");
        //alert('Overlay Activated');
    } else if (elementClassName == "OverlayBoxActive") {
        overlayBox.setAttribute("class", "OverlayBoxInactive");
        //alert('Overlay Inactivated');
    }

}

Thank you in advance for any assistance,

-Realitiez

EDIT POST: http://jsfiddle.net/bk5e9t0e/

Answer №1

When you use an input type="submit", the form's data is typically sent back to the server and the page reloads, resulting in the removal of your class.

To avoid this page reload, you can prevent the default action by returning false in the onclick handler:

onclick="ActivateOverlay(); return false;"

Answer №2

The reason your code wasn't working:

  • You used type=submit for the input, which caused a page refresh effect. It should have been type=button or included return false; in the click handler.
  • You called the function ActivateOverlay before it was defined.

Check out the solution on jsFiddle below

<script>
    function ActivateOverlay() {
        //alert('Overlay Activated');

        var overlayBox = document.getElementById("OverlayContainer");
        var elementClassName = overlayBox.className;

        if (elementClassName == "OverlayBoxInactive") {
            overlayBox.setAttribute("class", "OverlayBoxActive");
            //alert('Overlay Activated');
        } else if (elementClassName == "OverlayBoxActive") {
            overlayBox.setAttribute("class", "OverlayBoxInactive");
            //alert('Overlay Inactivated');
        }
    }
</script>
<div id="OverlayContainer" class="OverlayBoxInactive"></div>
<div class="main"></div>
<fieldset>
    <form>
        <input type="button" onclick="ActivateOverlay();return false" value="Hit Me"></input>
    </form>
</fieldset>
<script type="text/javascript" src="index.js"></script>

http://jsfiddle.net/4queag8m/

Answer №3

To avoid the page from reloading, make sure to include a preventDefault() in your function code.

Begin by adding the element to your call:

onclick="ActivateOverlay(this)"

Then, include the prevent parameter in your function like so:

function ActivateOverlay(evt) {
    evt.preventDefault()

    // Your code here
}

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

Encountering the error message "The function $(...).tablesorter is not defined" while using webpack

After updating to Rails 6 with Webpack, I'm encountering the error message Uncaught TypeError: $(...).tablesorter is not a function. Below is the snippet of my environment.js file: const { environment } = require('@rails/webpacker') const w ...

Import .vue single file component into PHP application

I've been struggling to integrate a .vue single file component into my php app without using the inline template method. Since I don't have a node main.js file to import Vue and require the components, I'm not sure how to properly register m ...

How to extract IDs from a URL in Angular

I'm facing an issue with retrieving the first id from an image URL. Instead of getting the desired id, I am receiving the one after the semicolon ("id" = 1). I have tried various methods but haven't been successful in resolving this issue. Any su ...

Using HTML to create interactive table cells

I am looking to add functionality to make a cell in an HTML table clickable. When this action is triggered, I want a pop-up or window to appear with specific information. Below is my current HTML code: <table class="table1"> <thead> <tr ...

Is there a way for me to view the specifics by hovering over a particular box?

Whenever I hover over a specific box, detailed information appears, and when I move the mouse away, the details disappear. HTML <nav> <div> <div class="nav-container"> <a href="./about.html" ...

Interactive HTML5 map featuring geo tagged points

Seeking an HTML5-based tool to efficiently display a zoomable, panable map (similar to Google Maps) and incorporate a circle at a specific location upon clicking a button on a webpage. Any suggestions for HTML5-compatible frameworks or would JQuery be the ...

Unit testing an Angular service using Jasmine with a JSON object schema in Angular 2/4

Looking for assistance with unit testing a service I have. The service includes a current json array object that is functioning properly when the observable is subscribed to. However, I seem to be encountering issues with my unit test setup. Can anyone pr ...

Customizing Marker Images in Google Maps JavaScript API

Currently, I am using a workaround to rotate a custom image marker in Google Maps. The issue I am encountering is regarding sizing. For example, if my PNG image is 400px wide and 200px high. When rotating the image so the width becomes vertical, it gets ...

The complexity surrounding various versions of jQuery, the .noConflict method, and the jQuery migrate feature

I was tasked with making a large-scale website responsive, and decided to utilize Bootstrap as the framework. However, I encountered issues due to the jQuery version (v1.8.2) being used. In my development environment, I resolved this by including the follo ...

The function insertAdjacentHTML does not seem to be functioning properly when used with a

I am working with a parent element that contains some child elements. I create a DocumentFragment and clone certain nodes, adding them to the fragment. Then, I attempt to insert the fragment into the DOM using the insertAdjacentHTML method. Here is an ex ...

Changing font styles using the jMenu jQuery plugin: A step-by-step guide

I'm having trouble changing the font-family using CSS with jQuery's "jMenu" plugin. Here is the CSS I currently have: .jMenu{ position : absolute; top : 80px; left : 0px; width : 100%; display:table; margin:0; padding ...

"Upon requesting three gltf files, the response was found to

Currently, I am utilizing the GLTF loader for the purpose of importing a custom model into my scene. Within my codebase, there exists a class called Spaceship.js that manages the loading of the model. // Spaceship.js import { GLTFLoader } from 'thr ...

How does JavaScript function syntax differ in Next.js and JSX?

I'm in the process of creating a function that allows users to select different sizes. It currently works fine with just JavaScript and HTML, but I'm encountering an error when using it in Next.js. Can someone confirm if my syntax for the JavaScr ...

When the parent element's CSS property is set to display: none, ng-repeat fails to function

I have a division with a specific class in the CSS named display: none;. When I click on a button, I switch the class using a toggle class feature called ng-class="vm.showing ? 'zoomIn' : 'zoomOut'". The issue arises when Angular does n ...

Renew the id_token in the front-end: Angular 4

I am currently utilizing the ng2-adal npm library to create id_token and access_token. As the id_token is valid for 30 minutes and the access_token for 60 minutes, my goal is to automatically refresh the id_token every 20 minutes in the background. One pot ...

Sending Parsed Information to Callback for Flexible Use

Is there a way to pass the value of coins, or even better, currency to my callback function so I can freely use the parsed JSON data in other functions? function fetchJSON(path, callback) { var jsonReq = new XMLHttpRequest(); jsonReq.onreadystatechang ...

What is the best way to ensure form submissions in jQuery include non-empty inputs?

Is there a way to only send non-empty inputs (those with values not equal to "") when a user submits a form? I want to achieve this because my website offers forms for filtering data, using the GET method to indicate query strings in the URL. However, som ...

Excessive content causing an overflow within the table and extending the length of

My page is currently overflowing its length compared to the main table, and I want it to be as long as the table. The issue seems to be related to the code snippet below: thumbnail { padding: 0; background-color: transparent; transition: transfo ...

Getting form field values with JQuery

I am currently facing an issue with a form field in HTML. Here is the code snippet: <form id="tasklist"> <input type="text" id="name" ...></input> ... additional form elements go here ... </form> Although I am trying to retrie ...

Wave your way to unique text creation with Firefox

Hey there, I've got some text inside a div that's been transformed with rotate(3deg). Strangely enough, in Firefox, the text appears wavy. When I remove the transform property from the div, the waviness disappears. Is there any way for me to keep ...