JavaScript code to perform various functions

Suppose I am implementing the following JS Code:

<script language="javascript" type="text/javascript">
     function toggleVisibility() {
        var element = document.getElementById("elementId");
        if(element.style.visibility.toLowerCase()=="visible" || element.style.visibility == "") {
            element.style.visibility = "hidden";
        } else {
            element.style.visibility = "visible";
        }
    }
</script>

and then using this HTML code:

<a href="#" class="Action" id="action" onclick="return toggleVisibility();">Toggle Menu</a>
    <div id="elementId" style="visibility:hidden">
     content here
     </div>

What is the optimal way to add another div with a link that expands the same div without duplicating the function?

Answer №1

Here is a simple way to toggle the visibility of a div using JavaScript:

function toggleVisibility(id) {
  var element = document.getElementById(id);
  
  if (element.style.visibility === 'visible' || element.style.visibility === '') {
    element.style.visibility = 'hidden';
  } else {
    element.style.visibility = 'visible';
  }
}

To use this function, just pass the id of the element you want to show/hide:

<button onclick="toggleVisibility('myElement')">Toggle Visibility</button>

Check out this demo to see it in action.

Answer №2

Explore:

function toggleVisibility(targetDiv) {
    var element, style, hidden;
    element = document.getElementById("elementId");
    style = element.style.visibility;
    hidden = style.toLowerCase() == "visible" || style == "" ? false : true;
    element.style.visibility = (targetDiv === true || (hidden && targetDiv !== false) ? 'visible' : 'hidden')
}

How to use:

toggleVisibility() // Toggles visibility to opposite of current state.
toggleVisibility(true) // Always shows the specified div.
toggleVisibility(false) // Always hides the specified div.

Example: http://jsfiddle.net/d2jkq/

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

The directive 'templateUrl' points to the route '/'

I'm having an issue with using the templateUrl in a directive to load a partial. Whenever I try to visit the URL for the template, it redirects me back to /. This results in the partial loading the entire page instead of just the requested partial. a ...

Angular Material UI dropdown menu

Currently, I am in the process of incorporating a select dropdown using Angular Material UI. <md-select class="width-100" placeholder="Priority" data-ng-model="task.priority"> <md-option value="one">One</md-option> <md-option ...

Using document.write, adding elements to an Array with Array.push, and concatenating

I need my code to be able to update the current HTML page visible to the user using document.write(). Although it successfully updates the HTML page, it doesn't display the desired text. When I utilize my code to insert an element using the addElement ...

Creating dynamic div elements using jQuery

I used a foreach loop in jQuery to create some divs. Everything seems to be working fine, but for some reason, my divs are missing SOME class properties. Here is the code snippet I am using: $("#item-container").append("<div class=\"panel col-md-2 ...

What methods can I utilize to prevent pop-up errors from appearing in my javascript code?

Recently, I've been working on utilizing an innovative IBM tool called Presto that efficiently transforms traditional green screens into browser-based pages. While the process is effective, it involves some quirky behaviors. One particular challenge I ...

What is the process for building a JSON-formatted dictionary?

My intention is to structure my data in a way that can be accessed using a specific key. The current arrangement looks like this: const dict = []; dict.push({"student": "Brian", "id":"01", "grade":& ...

Require that JSX elements begin on a new line if the JSX element spans multiple lines

Which eslint rule favors the first syntax over the second when JSX code spans multiple lines? Currently, Prettier is changing `preferred` to `notPreferred`. const preferred = ( <tag prop={hi} another={test} \> ); const ...

JQuery is unable to locate the buttons within the parent div of a reference div

Currently utilizing JQuery version 3.6.1, my objective is to retrieve Buttons 1 & 2 through JQuery. <div class="parent" role="dialog"> <div id="Dialog"/> <div class="buttonPane"> <div cla ...

I am able to craft a function that takes in an integer and produces an array filled with pairs of integers [a, b] arranged in ascending order of both a and b

I'm currently stuck on a practice problem in my software engineering bootcamp and could really use some help to steer me in the right direction. The task is to create a function called generatePairs that takes an integer as input and returns an array ...

Issue arises when incorporating accordion toggle with navtabs (Bootstrap)

Currently, I am working on a navigation layout using Bootstrap that will be displayed as tabs on desktop and as an accordion on mobile devices. The setup is almost complete, but there is an issue that I'm struggling to resolve. The problem arises whe ...

I am currently working on a website that offers different themes, and I am attempting to update the iframe to reflect the selected theme on the site

I'm feeling lost on how to accomplish this task. Despite my efforts, I have been unable to find a solution so far. Perhaps utilizing javascript might be the key here, yet I am uncertain about integrating it into the existing script that I use for modi ...

Tips on using CSS to hide elements on a webpage with display:none

<div class="span9"> <span class="disabled">&lt;&lt; previous</span><span class="current numbers">1</span> <span class="numbers"><a href="/index/page:2">2</a></span> <span class="num ...

Issue: Unable to access the 'Stream' property as it is undefined in the AthenaExpress.query function due to a

I'm currently attempting to establish a connection with AWS Athena and run a select query using the athena-express package. However, I encountered the following error: Error: TypeError: Cannot read property 'Stream' of undefined at AthenaEx ...

Terminate a targeted recipient following the completion of the on event

I am currently running a node service with socket.io and utilizing an event emitter to send updates based on user context. For example, context A may have users 1, 2, and 3 while context B has users 4 and 5. Once a successful connection is established wit ...

React-Native 0.1.17 Navigator Bar: Enhancing User Navigation Experience

An issue arose after upgrading my react-native 0.1.15 app to version 0.1.17 - I'm now encountering an 'Unable to download JS bundle error'. Upon investigation, I found the error in my code: var SportsSocial = React.createClass({ component ...

Updates to Providers in the latest release of Angular 2

When working with angular 2.0.0-rc.1, we implemented a Provider using the new Provider method as shown in the code snippet below: var constAccessor = new Provider(NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => EJDefaultValueAccessor), ...

Unable to retrieve property from NextRequest

Currently, I am attempting to utilize MiddleWare in conjunction with Next.js's Middleware and JWT. Upon logging cookies and the typeof cookies variable, this is what I see on my console: { token: 'token='myToken'; Path=/' } obj ...

Adjust the range directly in ng-repeat from the directive

I am working with HTML code that looks like this: <div dir-paginate="x in comments | itemsPerPage: commentsPerPage"> HERE IS DIRECTIVE FROM BLEOW </div> My goal is to update the commentsPerPage scope within the directive... Below is a direct ...

Guide to converting a D3js Bar Chart race into an MP4 or video file

https://i.sstatic.net/5Ri0T.jpg let competition = d3.interval(function() {}, tickDuration); ...

Passing a click event to a reusable component in Angular 2 for enhanced functionality

I am currently working on abstracting out a table that is used by several components. While most of my dynamic table population needs have been met, I am facing a challenge with making the rows clickable in one instance of the table. Previously, I simply ...