Using JavaScript Functions to Resize Buttons and Change function on Click

I have a button in my code that triggers CSS changes by adding and removing classes. The JavaScript for this function works as intended - clicking once adds the class, clicking again removes it, and so on.

However, I also implemented a feature to remove these classes if the browser window is resized. The problem arises when I resize the window and then try to click the button again. It seems to register the second click (even though the classes were removed due to resizing), essentially reversing the function. What I really need is for the button function to reset after resizing, starting from scratch as if it hadn't been clicked before.

I hope this explanation makes sense, as I've been struggling with this issue for a while now and haven't found a solution that works as desired.

Any assistance would be greatly appreciated!

Below is the code snippet:

JS/jQuery

{
  /* Button Function to add and remove classes */

  $("#nav-icon").click(function () {
    var clicks = $(this).data("clicks");
    if (!clicks) {
      $(".logo-container").addClass("border-change-image");
      $(".container-fluid").addClass("border-change-header");
    } else {
      $(".logo-container").removeClass("border-change-image");
      $(".container-fluid").removeClass("border-change-header");
    }
    $(this).data("clicks", !clicks);
  });


  /* Window Resizing Function */

  $(window).on("resize", function () {
    var size = $(this).on("resize");
    if (size) {
      $(".logo-container").removeClass("border-change-image");
      $(".container-fluid").removeClass("border-change-header");
    }
  });
}

Answer №1

Revamped the code by eliminating the variable holding the data and simply checking if a specific div has certain classes before adding or removing them. The result is flawless execution.

JavaScript

$("#nav-icon").click(function () {
    if ($(".logo-container").hasClass("border-change-image")) {
      $(".logo-container").removeClass("border-change-image");
      $(".container-fluid").removeClass("border-change-header");
    } else {
      $(".logo-container").addClass("border-change-image");
      $(".container-fluid").addClass("border-change-header");
    }
  });

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

Adjusting the transparency of one element and rotating another element that are the same size

This issue is driving me nuts: I'm attempting to rotate the border of a circle element and simultaneously adjust the opacity of the circle overlay when a user hovers over it. However, in my current setup, only the opacity changes: <div id="main-c ...

Manipulating the visibility of components by toggling on click events according to the existing state in ReactJS

Disclosure: I am still getting familiar with ReactJS I'm currently working on incorporating a dialog window for selecting a country/language on the initial page of my application. Here's the concept: There's a small flag button in the to ...

The navigation menu dissolves into hiding at the uppermost part of the page upon scrolling upwards on iOS devices

I am currently working on creating a navigation menu that will automatically hide when scrolling down and reappear when scrolling up. This functionality works perfectly fine on desktop and Android browsers, but I have encountered an issue specifically with ...

Encountered CSRF validation error while working with a Python Django backend in conjunction with React frontend using Axios for making POST requests

I recently completed a tutorial at and now I'm attempting to add a POST functionality to it. Despite obtaining the csrf from cookies and including it in the "csrfmiddlewaretoken" variable alongside a test message in json format for the axios function ...

How can I ensure that the form submit event is delayed until the onChange event is completed when using jQuery?

Imagine a scenario where a textbox on a webpage has a 'change' event attached to it using jQuery. $('.myFormClass').on('change', '.amount', function () { // An AJAX call is made here, and the respons ...

The padding of elements changes accordingly as the dimensions (width/height) of the header are adjusted

Currently, I'm tackling the challenges of working on my website and trying to understand JavaScript better. I am facing an issue where I want my aside menu's padding to adjust when my header shrinks in height. Furthermore, at the end of the web ...

What could be the reason for the lack of error handling in the asynchronous function?

const promiseAllAsyncAwait = async function() { if (!arguments.length) { return null; } let args = arguments; if (args.length === 1 && Array.isArray(args[0])) { args = args[0]; } const total = args.length; const result = []; for (le ...

Mobile FPS suffering due to slide-out drawer performance issues

My application features a drawer menu that functions smoothly on desktop, but experiences issues on mobile devices with noticeable lag. Within the header, I have implemented a boolean value that toggles between true and false upon clicking the hamburger i ...

Enlarging a JSON structure exported from Clara.IO using Three.js

As a beginner in Three.JS, I have been honing my skills in creating scenes and models. Recently, I imported a washing machine model into my scene and positioned it accordingly. Now, I am trying to scale it up to make it larger, but I am unsure of how to do ...

Use jQuery to create a toggle effect with unique attributes and incorporate AJAX functionality

When using this jQuery plugin for creating toggles, I encountered an issue with multiple toggles having the same IDs and classes. This made it difficult to identify a specific toggle to apply auto load ajax when the value changed. I'm wondering how I ...

AngularJSError

I am completely new to AngularJS and I've been tasked with debugging someone else's code. While debugging in Google Chrome, I encountered the following error: TypeError: accountService.logIn(...).success is not a function. The issue lies with ...

I am encountering an issue where my ejs file is not rendering properly even after moving my static files to the public folder and including the line of code app.use(express.static("public")). Can anyone help

After relocating the index.html and css files to the public folder and adding app.use(express.static("public)) in app.js, everything was working fine and the list.ejs was rendering correctly. However, there seems to be an issue now. const express = re ...

Visit the map only after the promises have been fulfilled

In my current project, I am utilizing the loadash map function for data structuring. The data retrieved consists of a series of IDs that require querying the database and integrating the results into the map before returning. However, the data is delayed i ...

Trouble with submitting a form and showing a success message in AngularJS version 1.6.8

My query submission form consists of fields for name, email, and the actual query. The component includes a controller function with a submit function to handle form submission. To submit user input and display a success message upon submission, I utilize ...

ridiculing callback within parameter

I have a model setup in the following way: export class MyClass { grpcClient: MyGRPCClient; constructor(config: MyGRPCClientConfig) { this.grpcClient = new MyGRPCClient( config.serverUrl, grpc.credentials.createInsecure(), ); ...

Conditions for JQuery Ajax handlingIs there anything specific you would

I am looking to implement a try-catch scenario in Laravel where, if successful, a certain message will appear and if it fails, a different message will be displayed. However, when executed successfully, it seems to display the second message instead. $.a ...

How do I assign a variable to a session in Express.js?

I am currently working on a login form that prompts users to enter their username, password, and company name. The company name corresponds to the database name, so I need to store this information in the session during the login post request. In my opini ...

React fails to recognize the key prop

When creating a list of TSX elements, I utilized the following code: this.productsModel = this.state.products.map(o => ( <Grid.Column key> However, I encountered a warning from React: Warning: Each child in a list should have ...

Launching the webpage with Next.js version 13

Hey there! I'm currently working on implementing a loading screen for my website to enhance the user experience. Since it's quite a large site, I believe a loading screen would be beneficial. However, I'm having trouble getting it to work on ...

What is the process for writing <p></p> and showcasing it on your website?

Is there a way to display the code <p></p> as text on an HTML page without it being processed as HTML, resulting in an empty paragraph? ...