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

How can I retrieve the URL of the previous page from the history object in all browsers?

Can we retrieve the URL of the previous page from the history object? I've seen references to history.previous, but it appears to be either undefined or protected based on my observations. ...

Is AJAX malfunctioning while the success function is functioning properly?

the function for success is operational, however the data isn't being saved in the database $(document).ready(function() { $("#ChatText").keyup(function(e){ if(e.keyCode == 13) { var ChatText = $("#ChatText").val(); ...

Avoiding layout shift when a button is clicked in React JS

I am working on a Drawer example and following the instructions provided at https://mui.com/material-ui/react-drawer/ Everything is functioning as expected, but I am encountering an issue where my content shifts to the right when the drawer opens, and ret ...

What's the connection between CSS and frameset?

Currently, I have an .html document with XHTML 1.0 Frameset doctype and the following code: <frameset rows="20%, 80%" border="1"> ... </frameset> Upon validating this code on W3C Validator, it gives me the error message: there is no a ...

"Exploring the process of implementing a fixed method POST in Angular 5

When developing an application for Portal, I encountered an issue where a newly created role is not displayed without refreshing the browser. How can I ensure that the added element is directly displayed in the table without needing to refresh the browser? ...

The code functions properly within the emulator, however, it fails to execute on an actual device

Yesterday, I posted a question about the background related to this topic: on click event inside pageinit only works after page refresh. I received an answer for my question and tested it in Chrome devtools where it worked perfectly. However, today when ...

Issue with Jade not displaying external JSON data

I am struggling with a jade template that is supposed to display all possible solutions from the QPX Express search request: { kind: 'qpxExpress#tripsSearch', trips: { kind: 'qpxexpress#tripOptions', requestId: 'RwDOf6H ...

Integrating XML API Requests Using HTML and JavaScript

When there is only one item in the XML document, I want to update my inner HTML with the result of an API call. I have managed to successfully make the API call work when there are multiple items in the XML document (thanks to W3). <!DOCTYPE html> ...

What is the most effective way to transfer information from one page to another in a PhoneGap application?

I attempted to transfer data from one HTML page to another using two different methods: function reply_click(clicked_id) { window.location = "newsList.html?Title="+clicked_id; } And I also tried: function reply_click(clicked_id) { window.l ...

Troubleshooting directive not functioning properly with AngularJS ng-click

My HTML img tag is not responding to ng-click when clicked. I'm puzzled by this issue occurring in masonryPictureView.html Main page - home.html <ng-masonry> <ng-picture ng-items="projectdescription.pictures"></ng-picture> </n ...

Guide to filling out select dropdowns in HTML with information from a database

I'm new to PHP and HTML, so please be patient with me. I've been attempting to populate a select box using data from a MySQL database, but all I see is an empty textbox. Here's my current code: <select name="cargo"> <?php ...

The callback function in JavaScript seems to be missing without ever being executed

I have a SendMail function using nodemailer that successfully sends emails, but the callback function logging "mail sent" is not getting executed. Any suggestions on what might be causing this? var email = '<a href="/cdn-cgi/l/email-protection" cla ...

The issue with Node.js router failing to process delete requests

My Node.js router is handling all methods well except for the DELETE method. I can't figure out why the delete request does not reach the router. The AJAX request seems to be functioning correctly. AJAX request: function ajaxHelper(url, onSuccessAr ...

Unable to save data retrieved using jQuery JSONP

My current project involves fetching photo data from Flickr using a jQuery AJAX call with JSONP. However, instead of immediately using the data, I want to store it for future use. In some cases, users will be able to perform different queries on the pre-fe ...

What is the process for enabling SASS line numbers using Yeoman's Grunt.js file?

Recently, I used Yeoman (1.4.5) to scaffold a new web application. Within my Gruntfile.js, I configured it as follows: ... // When requested, compile Sass to CSS and generate necessary files sass: { options: { lineNumbers:true, sourceMap: true, ...

Dealing with errors when working with cross-domain JSONP requests in jQuery can be a

My attempts to capture a bad request error using my jquery code have been unsuccessful. $.get('http://example.com/', {}, function () {}, 'jsonp') .done(function () { // never fires }) .fail(function () { // never fires }) .a ...

Do I need to use the "--save" flag in npm to add dependencies to the "package.json" file?

Do I really need to use the "--save" flag in order to add an installed dependency to the "package.json" file? I conducted a test without the "save" flag and found that the package was still added to the "dependencies" section. It seems like it is the defa ...

Experiencing difficulty in connecting with the service providers

What's the process for obtaining these providers? I recently followed the JavaScript Mastery tutorial step by step, however, I encountered an issue with the useEffect hook to fetch the providers (I even tried using alert to check, but it keeps showin ...

Express server controller encountering premature return from locally executed async function

I have developed an API endpoint using Node/Express. I am trying to call a local function asynchronously within the controller function, but instead of receiving the expected asynchronous results, the called local function is returning undefined immediat ...

Navigate to a different page using an AJAX request

Is it possible to use ajax for redirecting to another page? Here's the code I've been working on: <script type="text/javascript"> $(document.body).on('click', '#btnPrintPrev', function() { $.ajax({ url: &apo ...