"Error: The .cssText method in Javascript is not working properly

I have been encountering an issue where the .cssText is not updating the HTML element referred to as .unveil. I implemented an event that when the container for .unveil is clicked, the .unveil element should become visible. However, upon clicking the .unveil element, it should hide itself. Despite this setup, whenever I run the program, I am informed that the values are not being overridden.

Here is the function; there are no error messages shown:

function unveilAnswer(){
     // let's add the flip functionality for showing the answers
    var unveilNode=null;
    for (i=0; i<containerCards.length; i++)
        if (this===containerCards[i]) {//"this" in this case refers to the object that the event is being added to; it will be from the .container-card perspective
            unveilNode=this.querySelector(".unveil");
            this.addEventListener("click", e=>{
                unveilNode.style.cssText="display:block; height:95vh; width:95vw;";
            });
            unveilNode.addEventListener("click", (e)=>{
                unveilNode.style.cssText=" display:none; width:0px; height:0px;";
                showCards(); //for when it's time to click on another question; it will hide the current one
                console.log(unveilNode); // fpr testing purposes
            });
            hideCars(i);
        }
}

After clicking on the container for .unveil, the size changes due to the inline CSS modifications. However, when the .unveil element is clicked, nothing happens...

<div class="unveil" style="display: block; height: 95vh; width: 95vw;"> 
    <p>test!</p>
</div>

Once the .unveil element displays on the screen and I try to click on it, the height and width do not change despite having a "click" event listener installed. I even attempted using .style.height and .style.width with no success. My query now is why isn't .cssText functioning properly as expected?

Answer №1

To prevent multiple firing of an event listener, ensure that you only add it once and use 'removeEventListener()' when needed. You can set up a class like .hidemycard { display:none } and then toggle it using

unveilNode.classList.toggle('hidemycard')
to show/hide the element on each click.

Here's an example code snippet demonstrating how to implement this:

window.onload = (event) => {
  const card = document.getElementById('me');
  card.addEventListener('click', () => {
    document.getElementById('thingtoshow').classList.toggle('hideme');
  });
}
#me {
  cursor: pointer;
}

.hideme {
  display: none;
}
<div id='me' class='card'>Click me!</div>
<div id='thingtoshow' class='hideme'>This is some content!</div>

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 could be causing the render to not appear? Using Aframe with three object3D elements

I am having trouble rendering a threejs object in aframe. What steps should I take to successfully render the object? html <a-scene> <a-entity geometry material id="obje"></a-entity> <a-entity camera id="cam"&g ...

Customizing Nav Bar Color in Bootstrap

Is there a way I can change the font color of the Nav Bar to white? I'm having trouble figuring out which CSS class to use for 'Contact', 'Portfolio', and 'About' as 'Navbar' is already white due to Bootstraps&a ...

Guide: Writing code that caters to different types of media in React using Material-UI

After reviewing the documentation, I believed that the optimal solution in later versions of material-ui was to use useMediaQuery, but unfortunately, I am unable to implement it correctly. My objective is to hide a menu when the page is being printed, so I ...

Clicking on a list item in React's material design will illuminate the item, marking it

I have 2 panels with a list group on each panel, following material design guidelines. Concern: When clicking the first list-item on panel 1, it does not get selected and change to style = "success", or highlight the selected item. The same issue occurs ...

Simple Steps for Dynamically Adjusting Table Cells without Disturbing Existing Data

Is there a way to make a table automatically arrange cells in rows of two, adjusting as necessary when adding or removing cells (with one cell in the last row if there is an odd number of total cells)? For example: <table> <tr> <td>o ...

Error encountered when utilizing a specialized jQuery extension: "not a function"

Every time I attempt to execute this function (function($) { $.fn.generateURLHash = function() { return document.URL.substr(document.URL.indexOf('#')+1); }; })(jQuery); when I call $.generateURLHash(), an error pops up in th ...

Error message: Issue encountered while rendering Angular Bootstrap accordion template

Despite my attempts to find a solution before reaching out for help, I am struggling to get the accordion feature to work in my Angular and Bootstrap application utilizing ui.angular.js. The error message in the developer tools indicates an issue with the ...

Ensure that the text inside the button does not exceed its boundaries (utilizing Bootstrap v4)

My current code snippet appears below. <div class="col-xl-2 col-lg-12"> <button class="btn btn-secondary w-100" value=1>But.</button> </div> <div class="col-xl-4 col-lg-12"> <button cla ...

Hover state remains persistent even after modal window is activated in outouchend

One of the buttons on my website has a hover effect that changes its opacity. This button is used to share information on Facebook. It's a simple feature to implement. Here is the CSS code: .social_vk, .social_fb { height: 38px; obj ...

JavaScript: A step-by-step guide to extracting the file name and content from a base64 encoded CSV

I have a base64 string that was generated by encoding a csv file, const base64 = 'LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLTExNDc2MDgwNjM5MTM4ODk4MTc2NTYwNA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWxlIjsgZmlsZW5hbWU9ImNoYXJ0T2ZBY2NvdW50LmNzd ...

Utilizing Multiple Select Options and CSS Float Styling in Mozilla Firefox

I have been attempting to customize the CSS of a multiple select element. While I am satisfied with how it looks on Chrome, I am facing issues getting it to work correctly on Mozilla Firefox. $('option').mousedown(function(e) { ...

The Node.js server pauses its listening activities until the promise, which involves an asynchronous function that runs a loop with the goal of making it operate in the background, is

My server code is set up to listen on a specific port: app.listen(PORT, () => { console.log(`Server running on ${PORT}`); }); When a request is received, it is sent to a function for processing: app.get("/", (req, ...

Trigger a function when <a> is clicked, which will then increment the count by one and reflect this change in the database

The database generates the content of this div ordered by a count number called "cts". Whenever I click on the div, I want the "cts" number to increase by one, and then update the change in the database. This will result in the content changing accordingly ...

Conceal/Reveal the ng-grid?

I have a setup with multiple tabs, where I want to display different content. Specifically, I would like one of the tabs to show an ng-grid when clicked, while hiding the grid if any other tab is selected. I attempted using ng-show and setting boolean va ...

Trigger the function upon displaying the modal

Within my Bootstrap project, I have set up a click event to trigger a modal as follows: $('#make_selects_modal').appendTo("body").modal('show'); My requirement is to run a function called pickClient when this modal is displayed. I att ...

Bootstrap responsive breakpoints for different sizes

As I was optimizing my webpage, everything was going smoothly until I had the idea to incorporate the srcset and sizes attributes into my <img> tags. I developed a php function that generates an img object and populates the srcset attribute with newl ...

Tips on transforming String Format information

My Json data is structured like this: var d = "1,3,2,4" I want to convert it to: var d = [3,5,3,6] I attempted the following: success: function (Response) { debugger; var du = (Response.d); var final_string = '[' + du + &apo ...

How to Retrieve URL Before Closing a jQuery Window Using window.open()?

Is it feasible to retrieve the URL of a window.open window after triggering a window.close event when the user clicks the close button? How can I obtain the last URL visited right before the window closes? ...

Troubleshooting: Issue with Updating Prototype Ajax Function

I am currently utilizing Prototype within the pylons framework and attempting to execute an Ajax call. Below is the structure of my html: <form method="POST" action = "javascript:void(0)" onsubmit = "new Ajax.Updater('graph','/saffron_m ...

Enhance your app with the seamless navigation experience using Ionic 2

As a beginner in Angular2, Ionic2, NodeJS ... I am experimenting with writing some code to learn. In my journey, I attempted to create a screen with 3 tabs and a menuToggle. When the application is launched, clicking the menuToggle button on the first tab ...