javascript alter css property display to either visible or hidden

I am struggling with a CSS id that hides visibility and uses display: none. The issue arises when I want the element to be visible upon clicking a button, but removing the display:none property is causing design problems due to it being an invisible element.

My ultimate goal is to click a button and have certain elements disappear while others appear.

Below is the HTML code:

<div class="fwork1" id="fwork1">

    <a href="#portfolio" onclick="fWork1()">
        <img src="assets/img/portfolio/corinthmc/corinthmc_small.png" alt=""> 
    </a>

</div>

<div id="hwork1">

    <p>some text</p>

</div>

<div id="fWorkReturn">

    <button onclick="fWorkReturn()">Click</button>

</div>

And here is the relevant CSS code:

#hwork1 {
    visibility: hidden;
    display: none;
}

Finally, the Javascript code for handling the functionality:

function fWork1() {
    document.getElementById("fwork2").style.display = "none";
    document.getElementById("fwork3").style.display = "none";
    document.getElementById("fwork4").style.display = "none";
    document.getElementById("hwork1").style.display = "block"; 
}

function fWorkReturn() {
    document.getElementById("fwork1").style.display = "initial";
    document.getElementById("fwork2").style.display = "initial";
    document.getElementById("fwork3").style.display = "initial";
    document.getElementById("fwork4").style.display = "initial";
    document.getElementById("hwork1").style.visibility = "hidden";
}

You can view the complete code on JSFiddle here.

Answer №1

To effectively manage this situation, you should assign a class when the element is clicked. Your JavaScript code will resemble the following:

function activateWork() {
    document.getElementById("workElement").classList().add('active');
}

As for your CSS, it should include these rules:

#hiddenWork {
    display: none;
}

#hiddenWork.active {
    display: block;
}

Answer №2

Make the following changes to your code:

function hideDiscounts() {
  document.getElementById("discount1").style.visibility = "";
  document.getElementById("discount2").style.visibility = "";
  document.getElementById("discount3").style.visibility = "";
  document.getElementById("discount4").style.visibility = "";
}

function showDiscounts() {
  document.getElementById("discount1").style.visibility = "hidden";
  document.getElementById("discount2").style.visibility = "hidden";
  document.getElementById("discount3").style.visibility = "hidden";
  document.getElementById("discount4").style.visibility = "hidden";
}

Answer №3

Here is a simple way to alter the visibility of an element using JavaScript. The provided code demonstrates how certain elements can have their visibility properties changed when a designated function is triggered or a button is clicked. Adapting this technique for different scenarios should be relatively straightforward.

function hideFourAndShowSix(){
  let four = document.getElementById('four');
  let six = document.getElementById('six');
  six.style.setProperty('visibility', 'visible');
  six.style.setProperty('display', 'list-item');
  four.style.setProperty('visibility', 'hidden');
}
#six{
  visibility: hidden;
  display: none;
}
<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li id="four">Four</li>
  <li>Five</li>
  <li id="six">Six</li>
</ul>
<button onclick="hideFourAndShowSix()">Hide no. 4 and show no.6</button>

PS: Feel free to ask for additional clarification in the comments section ;).

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

Looking to eliminate the vertical spacing of the <hr> tag?

Summary: For a quick solution, just click on the image at the bottom. Greetings to everyone! I am facing an issue with two <div> elements that I need to separate using a <hr class="separator"> element. Below is the CSS code for the ...

javascript - Include new parameter in object literal and retrieve

I have a base object that I define using an object literal: var obj = { key1 : 'value1', key2 : 'value2' } Now, I want to pass this object to a function and extend it like this: myFunction( obj + { key3 : 'value3' ...

The output of JSTree's data.rslt.obj.text() function is an array of text values, not just the text from the specified node

I am facing an issue with the jstree where it is returning a concatenated list of node names when I try to rename a node, instead of just the text for the node I am renaming. The jstree is set up to load on demand. How can I ensure that only the text for ...

What could be causing the issue with the functionality of third-level nested SortableJS drag-and-drop?

I am currently utilizing SortableJS to develop a drag-and-drop form builder that consists of three types/levels of draggable items: Sections, Questions, and Options. Sections can be dragged and reorganized amongst each other, Questions can be moved within ...

How to change the image source using jQuery when hovering over a div and set its class to active?

I am working with a div structure that looks like this: <div class="row margin-bottom-20"> <div class="col-md-3 service-box-v1" id="div1"> <div><a href="#"><img src="path" id="img1" /></a></div> ...

Leveraging various routes to access data with a shared VueJS 3 component

Could you please review this code snippet: It displays two routes that utilize the same component to fetch content from an API. Main.js const router = createRouter({ history: createWebHistory(), routes: [ { path: "/route1& ...

Adjust the size of both the right and left price scales on TradingView Lightweight Charts

Is it possible to set a fixed width for both the right and left price scales on a chart? Let's say, 50 pixels for the right price scale and 70 pixels for the left price scale? For a working example, please visit https://jsfiddle.net/TradingView/cnbam ...

When the nesting in AngularJS ui-router becomes overwhelming

I've been in the process of refactoring a large application at work, and I've noticed significant similarities between different parts of the app that make me think nesting routes could be beneficial. However, as I continue to nest more and more, ...

I encountered a problem with routing in my MERN project while trying to implement a feature I learned from a YouTube tutorial

My first question on stackoverflow. To summarize: I followed a YouTube video and downloaded the course code from the GitHub link provided, but I'm encountering routing issues despite reading similar questions on stackoverflow. I've been followi ...

I can't see the presence of spin.js on my website

I am completely new to Javascript and I'm trying to implement a loading spinner on my website. Whenever users tap the screen, it takes some time to navigate to the desired URL, so we need a spinner to prevent them from tapping repeatedly. I decided t ...

What is causing the Jquery form submit event to not trigger?

I am attempting to use jQuery to submit a form. I need the form submit event to be triggered when jQuery submits the form. However, the submit event handler is not being called successfully after the form is submitted. Here is the code snippet: <html ...

Issue with Passport Google Oauth login redirection to successful route

I am currently following a tutorial on setting up Google Oauth in my Express app using Passport.js. The tutorial can be found here. Below are the routes defined in my server.js file: // Code snippet here The server.js file also imports configurations fro ...

Encountered an issue with undefined property when attempting to add a second value to an array of

I have been working on the following javascript code: var res = [{}]; for (var idx = 0; idx < json.length; idx++) { // if the environment is already entered in the result if (res[idx].env) { sails.log.debug('Enviro ...

Is it possible to return a promise within the .then function in AngularJS?

I have a unique service called "usersService". I want to create a special method that interacts with another custom service I built. This other service has two handy methods: getUser() and getCurrentUser(). The getCurrentUser() method relies on the injecte ...

Exploring the capabilities of ECMAScript generators within the Intel XDK Simulator

I am attempting to utilize a generator that has been declared using function* in Intel XDK. The simulate function within XDK is said to be based on Chromium, though it's difficult to determine the specific version ('about' box and similar fe ...

The element is being offset by SVG animation that incorporates transform properties

I'm working on creating a halo effect by rotating an SVG circular element using the transform rotate function. I've been using getBox to find the center point of the element, but when the rotation occurs, the overall image is getting misaligned w ...

Having trouble displaying the selection menu when using Angular Strap?

//test.js const dropdownMenu = document.querySelector('.dropdown-menu'); dropdownMenu.addEventListener('click', (event) => { alert(`You clicked on ${event.target.textContent}`); }); // index.html <div class="dropdown"> ...

What is the most effective method for determining if an object contains a particular property?

Can anyone advise on the best approach to check if an ajax response object has a specific property? I've done some research and it seems there are various methods to do this. One way is: if(ajaxResponse.hasOwnProperty('someProperty')){ ...

Updating state within a loop of properties in a React ComponentDidUpdate function

I have been working on a project where I needed to update the state after the componentDidMount lifecycle method. The props that I am expecting in the child component are only available at mount, so I can only update the state after that point. The only so ...

Struggling to incorporate a logic in ajax using Cakephp2

I have a website built on CakePHP2 and I am looking to incorporate an Ajax function that will redirect to another URL if a specific PHP condition is met. Otherwise, it should display an error dialog. The tutorials I found on Google are quite complex for me ...