Is there a way to undo an onclick event by clicking again?

function modifyWidth()
{
var element = document.getElementById("pop").querySelector('li:nth-child(3)');
if(element.style.width === "200px") {
  element.style.width = "500px";
} else {
  element.style.width = "200px";
}
}
</script>

This code is triggered by clicking an element.

<li onclick="modifyWidth()">

The width of the element changes from 200px to 500px when clicked. How can I make it so that a second click sets the width back to 200px??

Answer №1

To make things more efficient, it is recommended to utilize a CSS class in order to define the width of an element. This approach offers several advantages:

  • No need to specify the width in multiple places (CSS and JS), making it easier to maintain
  • No requirement to know the default width of the element, resulting in increased flexibility

For example:

CSS:

.wide {
    width: 500px;
}

HTML:

<li onclick="show(this)">...</li>

JS:

function show(elem) {
    elem.classList.toggle('wide');
}

VIEW DEMO

Take a look at the MDN documentation on classList for details on browser support. Additionally, you can explore alternative methods for managing CSS classes on elements in this informative question/answer post: Modifying an element's class with JavaScript

To delve deeper into event handling techniques (ways to attach event handlers, data accessible within event handlers, etc.), consider reading through the insightful articles available at quirksmode.org.

Answer №2

function display() {
    var element = document.getElementById("pop").querySelector('li:nth-child(3)'),
        length = parseInt(element.style.length, 10);
    if (length === 500) {
        element.style.length = "200px";
    }
    else {
        element.style.length = "500px";
    }
}

Alternatively, I might consider naming the function toggleDisplay and avoiding inline click handling.

Answer №3

Utilize a toggle variable

var switchControl = false;
function display()
{
    if(switchControl)
    {
        var item = document.getElementById("pop").querySelector('li:nth-child(3)');
        item.style.width = "500px";
        switchControl = !switchControl;
    }
    else
    {
        var item = document.getElementById("pop").querySelector('li:nth-child(3)');
        item.style.width = "200px";
        switchControl = !switchControl;
    }
}

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

Using HTML5 canvas to draw circles with additional metadata stored in variables

I'm designing a seating chart that will indicate spots with circles and show a tooltip on mouseover with the person's first name, last name, and possibly other details. I plan to use Kinetic.JS for region/tooltip support based on the tutorials I& ...

Unable to "serialize" geoJSON information

While working with Leaflet JavaScript, I am attempting to retrieve data directly from GeoServer using an Ajax link. To display it nicely in a DataTables table, I need to convert it into JSON format as per DataTables instructions. However, I keep encounteri ...

Error: Unable to access the 'login' property of an undefined object

An error occurred: Uncaught TypeError: Cannot read property 'login' of undefined........... import Login from '../components/Login.jsx'; import { useDeps, composeWithTracker, composeAll } from 'mantra-core'; export const com ...

Having trouble getting the onClick event to trigger in ReactJS buttons

The buttons are not functioning as expected, allowing for the addition of positive, neutral, or negative feedback. Interestingly, when I added a default button using different syntax to add negative feedback, it worked. This suggests that there may be an ...

Cannot access jquery within an angular directive

I've been attempting to incorporate jquery-ui's sortable feature on the elements within an ng-repeat loop. The issue I'm facing is that I am unable to actually perform the sortable action on these ng-repeat elements. I have searched for so ...

Can Vue.js support two-way data-binding without the use of an input element?

Here is the code snippet that I'm working with: <div id="app"> {{ message }} </div> JavaScript: myObject = {message:"hello"} new Vue({ el: '#app', data: myObject }) When I update myObject.message, the content within th ...

Discovering the anomaly within a set of values

I developed a function that can identify the outlier in an array consisting of a set of odd numbers and one even number, or vice versa. For example, findOutlier([2,6,8,10,3]) will return 3 as it is the only odd number in the array. Although I have success ...

Is there a way to ensure that an image stays pinned to the bottom of the screen, regardless of the device or screen

Looking for a solution to keep an image centered at the bottom of a website page regardless of screen size? I've tried different recommendations from Stack Overflow without success. position:fixed; bottom:0px; left:50%; Still struggling to make it wo ...

Using WEBGL to Showcase Your Images: A Step-by-Step Guide

I'm hoping to effortlessly showcase an image on the canvas at specific x and y co-ordinates using WEBGL, but I'm unsure of the process. Must shaders be included along with all other technical details? I've come across code snippets for displ ...

Empty screen appears when "npm run serve" command is executed following the build process

I am currently utilizing Material-ui. Following the project build with npm run build, I encounter a blank page when running npm run serve. I attempted to set homepage: "./" in the package.json as suggested here, however, it still displays a blank ...

Having trouble using Popper.js with Bootstrap 4 Beta in Webpack 3.x? You might encounter the error message "Popper is

Exciting news - Bootstrap 4 Beta has been released! However, Tether has been replaced with Popper.js for tooltip functionality (among other features). This change has triggered a new error in the console, prompting me to switch to Popper.js: Bootstrap drop ...

How to implement server-side rendering in Next.js 14 with GraphQL queries

I recently completed a Next.js project and configured Apollo Client. I integrated it with my components, as shown in my layout.tsx file: import { Inter } from "next/font/google"; import "./globals.css"; import ApolloProviderClient from ...

Ways to create more space between text and images with Bootstrap 5

Is there a way to adjust the spacing between descriptive text and an image on a webpage? I've tried fixing it, but it didn't work. How can I ensure that my text is properly separated from the image? Thank you. <!DOCTYPE html> <html lang ...

CreatePortalLink directs users to a payment URL instead of a dashboard

I am currently working on a project that utilizes the Stripe payments extension in conjunction with Firebase. The application is built using Next JS. After a user subscribes, I want to provide them with a tab where they can manage their subscription. The ...

The show.bs.modal event has been triggered when the .show() method is used on elements within the

Recently, I discovered that the event show.bs.modal is triggered not only when the modal itself is shown, but also every time you call the .show() method for an element within the modal. To attach the event handler, you would typically use the following c ...

Show the outcome of a function inside an ng-repeat loop

I have encountered a roadblock in my Angular project. I am populating a table with run data retrieved from a REST call using ng-repeat. Each run includes GPS coordinates, and I have a function that converts these coordinates into the corresponding city nam ...

What is the purpose of using the '@attributes' in the code while converting XML to JSON?

I have come across various iterations of the xml2json code that utilize the '@attributes' method, but I am wondering why not simply use obj[attribute.nodeName] = attribute.nodeValue instead? // Converting XML to JSON function xmlToJson(xml) { ...

Margin not being applied to last element in parent - any ideas why?

Why does the margin of the last element, whether it is a <p> or <h1>, not have any impact? It should be pushing the background of the parent container downwards. .container { background: grey; } h1 { margin-bottom: 3em } p { margin- ...

Encountering a plethora of errors post-updating Angular application from version 6 to 10

Could you please advise on the optimal method to update my application and provide a solution for peer dependency issues similar to the ones below: Package "ngx-chips" has an incompatible peer dependency with "@angular/animations" (requires "^8.0.0" (ext ...

Is there a way to conceal overridden div borders? When two divs are in conflict, eliminate borders only from the overridden region

I am facing an issue with two overlapping div elements. I need to remove the border from the area where they overlap only. Take a look at the code snippet below: <div style="width:100px; height:20px; background-color:#5475b1;border: 2px solid;" ...