changing the visible style of a div element using JavaScript

I'm having an issue with a link on my webpage that is supposed to show or hide a

<div id="po" style="display:none;">some html</div>
element. The first time I click the link, the div displays properly. However, after that initial click, the link stops working and I can't figure out why. I even tried setting the
<div style="display:block;">
and clicking the link caused the div to hide, but then it wouldn't show again. This behavior is puzzling to me as I have the exact same setup elsewhere on the page and it toggles correctly.

function po() {
  po = document.getElementById('po').style.display;
  
  if (po == "none") {
    document.getElementById('po').style.display = 'block';
    document.getElementById('po_Menu').src = "images/menu_dash.jpg";
  } else {
    document.getElementById('po').style.display = 'none';
    document.getElementById('po_Menu').src = "images/menu_plus.jpg";
  }
}
<img id="po_Menu" src="https://via.placeholder.com/50"> <a href="po()">show/hide</a>

Answer №1

It seems like you are replacing the function in this block of code:

po = document.getElementById('po').style.display;

By setting a new value to po, any future calls to po() will not work because it's no longer a function.

To avoid this, create a new variable instead:

const disp = document.getElementById('po').style.display;

Answer №2

It's important to be mindful of the naming conflicts and overwriting that can occur when using po. Inline styles should be avoided in favor of CSS classes, as they help streamline code writing and eliminate the need for unnecessary elements like the if statement. Hyperlinks should strictly be used for navigation purposes.

Here are some additional pointers:

const po = document.getElementById('po');

// Adding a "click" event handler to anything visible:
document.querySelector("#toggle").addEventListener("click", function() {
  // Using classes allows for more functionality with less code:
  po.classList.toggle("hidden");
});
/* Opt for CSS classes over inline styles whenever you can */
#toggle { text-decoration:underline; color:blue; cursor:pointer; }
.hidden { display:none; }
<img id="po_Menu" src="https://via.placeholder.com/50">

<!-- Avoid using hyperlinks as JavaScript "hooks". They should only be used for navigating. -->
<span id="toggle">show/hide</span>

<!-- Whenever possible, avoid inline styles and use classes instead. -->
<div id="po" class="hidden">some html</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

Obscure Promise Structure - Accomplish, Flop, Achieved

I came across the following code block and I'm struggling to understand it. While I have a good grasp on promises in the context of: deferred.then(successCb, errorCb); This code snippet appears to have three callbacks (complete, fail, done>) whic ...

Tokenizing with jQuery UI

I have been following a tutorial that utilizes jQuery UI to generate Facebook tokens, as shown in this link: However, I am facing an issue where I need to pass two values through JSON: the ID and the NAME. The server-side script is structured as follows: ...

Creating a dynamic background color that pulses with animation

I recently created a script to animate the menu li element when hovering over the corresponding a element. Everything is functioning as expected, but now I'm looking to enhance the effect by having it continue as long as the mouse remains over the a e ...

Is it possible to retrieve the HttpsError status from a Firebase function?

Within my firebase function, I deliberately throw an error with a specific status and message using the following code: throw new functions.https.HttpsError('permission-denied', 'Token does not match'); When I receive the server respo ...

Halt execution of routes using backbone.js

Is it feasible to halt route execution within backbone.js solely using the router? I understand there is a callback function for each route where I could verify if routing is permitted, but I am unsure how to prevent execution based on a property (such as ...

Navigate forward to the next available input in a grid by using the tab key

My goal is to improve form entry efficiency by using the tab key to focus on the next empty input field within a grid component. If an input field already has a value, it will be skipped. For example, if the cursor is in input field 2 and field 3 is filled ...

children blocking clicks on their parents' divs

I previously asked a question about a parent div not responding to click events because its children were blocking it. Unfortunately, I couldn't recreate the issue without sharing a lot of code, which I didn't want to do. However, since I am stil ...

Unable to sort the list items when utilizing the load() function

I have multiple li elements within a ul and I am using the following code to sort them in ascending order based on the data-percentage attribute: $(function() { $(".alll li").sort(sort_li).appendTo('.alll'); function sort_li(a, b) { re ...

Increasing the size of a background image as you scroll

Is there a way to adjust the background image of a div so that it scales according to the amount the page is scrolled? The current implementation works fine on desktop screens, but on mobile screens, the height of the background image reduces and the image ...

Next.js Error: The text displayed on the page differs from the HTML rendered by the server

Currently, I am facing an issue with the error "Error: Text content does not match server-rendered HTML." Here is my scenario - I have received a dateTime from an API, for example '2022-12-25T11:22:37.000Z', and I want to display it on a compone ...

Closing the Material UI Drawer

Having an issue with my material UI drawer - I can open it successfully, but when attempting to close it, the event does not trigger. import React from 'react'; import './App.css'; import { fade, makeStyles } from '@material-ui/co ...

Expanding CSS styles on hover

When my mouse pointer moves out of the red color box, it still triggers the hover function. However, I only want the hover effect to work within the red color box and hide the menu when it's outside the box. This is the source code from JSfiddle: htt ...

What could be causing this function to malfunction?

Apologies for any inaccuracies in technical terms used here. Despite being proficient in English, I learned programming in my native language. I am currently working on a project using the latest version of Angular along with Bootstrap. I'm unsure if ...

Exploring the integration of query parameters in Postman using mongoose

In my code, I have a driver.js file that holds a driver schema, and a driverController.js file with REST methods including GET, POST, DELETE, and PUT. What I want to achieve is to send a GET request to http://localhost:3000/drivers?available=true This re ...

Issue with Google Chrome not showing stylesheets on Windows 7

Recently, I've been facing an issue with CSS layers on my website while using Google Chrome. Despite following the code accurately, my browser fails to display the expected result. To troubleshoot, I even copied and pasted code from a reliable source ...

Can the html content provided by the user be extracted and highlighted?

When utilizing the onClick function in ReactJS, I am receiving the entire property which includes Lorem Ipsum is simply dummy text. However, I only require the highlighted content like "is simply dummy". Is there a way to achieve this?</p> ...

Parsing a Table in Python with HTMLParser

I am trying to convert an HTML table into a 2D array (rows and columns) using only the HTMLParser library in Python, without relying on BeautifulSoup or other non-standard libraries. This task is part of a personal project that I am working on for fun :) ...

The functionality of switching between two layouts using a JavaScript button is currently not functioning

My concept involves implementing a switch that alternates between displaying a bootstrap carousel and cards. Essentially, one of them will be visible when the button is pressed while the other remains invisible. Initially, I am attempting to hide my existi ...

Activate lightbox on click to swap image source temporarily

I have implemented the Materialize CSS "Material Box" lightbox plugin, but I am facing an issue. I want all the thumbnails to be uniform in size, and when clicked, the full photo should be displayed. Currently, I am using the onclick function to change th ...

Loading message displayed in web browsers by banner rotation system

I'm currently working on a banner rotator function that seems to be showing a "loading" message continuously while running. Here is the code snippet for reference: var banners = ['../Graphics/adv/1.gif','../Graphics/adv/2.jpg']; / ...