Tips on creating a Click handler function for multiple elements simultaneously

In my CSS design, I have multiple div elements that each need an onclick function. I would like to write the click function once and specify different actions based on whether the element clicked is an 'a' or 'b' element.

Can someone guide me on how to achieve this in jQuery?

$('.gil_Ads_BlankDock1').click(function(){ 

       // Hide various elements
       
 });

 $('.gil_Ads_BlankDock2').click(function(){ 

       // Hide various elements

 });

 $('.gil_Ads_BlankDock3').click(function(){ 

       // Hide various elements

 });

The code snippet above shows a few click functions that I want to optimize into a shorter version.

Answer №1

$('.notification_Ads_Dock1, .notification_Ads_Dock2, .notification_Ads_Dock3').click(function(){ 

       $('#adZone1').hide();
       $('#adZone2').hide();
       $('#descAd1').hide();
       $('#descAd2').hide();
       $('#descAd3').hide();
       $('#descAd4').hide();           
       $('#header').hide();
       $('#container').hide();
       $('#marquee').hide();           
       $('#BottomDock').fadeIn();
 });

Alternatively, if you are able to reorganize your HTML structure, consider assigning the same class "notifications" to your containers:

$('.notifications').click(function(){ 

       $('#adZone1').hide();
       $('#adZone2').hide();
       $('#descAd1').hide();
       $('#descAd2').hide();
       $('#descAd3').hide();
       $('#descAd4').hide();           
       $('#header').hide();
       $('#container').hide();
       $('#marquee').hide();           
       $('#BottomDock').fadeIn();
 });

You can also streamline your hide actions:

$('.notifications').click(function(){ 
       $('#adZone1, #adZone2, #descAd1, #descAd2, #descAd3, \
          #descAd4, #header, #container, #marquee').hide();           
       $('#BottomDock').fadeIn();
 });

Furthermore, consider assigning a common class "hidable" to the elements you want to hide:

$('.notifications').click(function(){ 
       $('.hidable').hide();           
       $('#BottomDock').fadeIn();
 });

If possible, adding these additional classes to your markup would be the most efficient approach.

Answer №2

Adding a +1 to all the responses provided previously. Another approach is to keep an array of selectors that need to be hidden if you are unable to refactor your code:

var elementsToHide = ['#gDescZone1','#gDescZone2','#descAd1','#descAd2',
               '#descAd3','#descAd4','#header','#contentArea',"#marquee"];
$.each(elementsToHide,function(index,value){
  $(value).hide();
});

Answer №3

$('.gil_Ads_BlankDock1, .gil_Ads_BlankDock2, .gil_Ads_BlankDock3').click(function(){ 

       $('#gDescZone1, #gDescZone2, #descAd1, #descAd2, #descAd3, #descAd4, #header, #contentArea, #marquee').hide();
       $('#BottomDock').fadeIn();
 });

Less code, more action :)

If only there was a way to minimize markup...

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

What strategies can be used to effectively combine Server-side postbacks with jquery's animations?

My ultimate goal is to create something that surprises me every time: I am in the process of developing an application in the same way I always have: using some <asp:LinkButtons> (or regular buttons), displaying content in Panels with <asp:Updat ...

What methods exist for determining the current location or city of a user without requesting permission?

Is there a way to automatically capture the user's current location on our website without explicit permission, possibly using IP address or MAC address? Has anyone successfully implemented this method in the past? ...

Retrieve information from a radio button that was generated dynamically and save it into an array

In my project, I have successfully created radio buttons using a for loop. This resulted in 10 sets of radio buttons, with each set containing 4 options. When the submit button is clicked, I am able to retrieve all checked radio values and store them in an ...

SQL select tag causing duplicated records to be inserted

Upon the first click event, no duplicate rows are generated After the second click, two rows are inserted Each subsequent click inserts an additional row Here is the HTML code snippet: <select class="form-control" name="select" id="select"> &l ...

Should the hourly charge schedule be based on user input and be created from scratch or utilize existing templates?

I have hit a roadblock while creating a charging schedule based on user input for my project. I am debating whether to search for and modify an existing plugin or develop it from scratch. The schedule involves solar charging electric cars between 7am and ...

Using the jQuery Validate plugin to verify a portion of a form

In my HTML form, I have multiple divs that represent the steps of a wizard. I am looking to validate only the active div when a "next" button is clicked using the jQuery.Validate.js plugin. Each div has its own ID, so I am trying to figure out how to achi ...

JS animation triumphant

I have developed an app that utilizes a checkbox to control the appearance of an overlay on a screen. To ensure smooth transitions, I have incorporated animations into the process. #overlay{ position:absolute; height: 100vh; width: 100vw; ...

Upon the initial loading of the site, the Material Icon will be displayed as the title

Encountering a problem with Angular 7 and materials icon where the name of the icon is visible during the initial load of the site. Does anyone know how to address this issue? https://i.sstatic.net/SkNVY.png ...

JSON retrieving a singular record exclusively

I am facing a dilemma with my code. When using a certain function, I retrieve hundreds of records but I am unable to add any additional information. Here is the code snippet: function(data){ $.each(data.products, function(i,item){ ...

What is the best way to change the class name using useState in order to trigger the required CSS conditions? Updating the tab ID appears to be

Just starting out with react/typescript (my third project). I'm currently working on a custom dynamic tab component. In this component, I dynamically create a class name to determine which tab is active and which is not. It seems to be functioning pr ...

Error encountered while invoking web server method in C# through ajax resulting in a 500 Internal Server Error

Occasionally encountering a 500 internal server error when calling a server method from an AJAX request has left me perplexed. The inconsistency of the issue, sometimes working fine and sometimes not, is baffling. To add to the confusion, no changes were m ...

Exploring discrepancies between two tables with the power of Javascript

const firstTable = document.getElementById('table_1') const secondTable = document.getElementById('table_2') const rows1 = firstTable.rows const rows2 = secondTable.rows for (let i = 0; i < rows1.length; i++) { for (let x in rows ...

Pop-up window triggered upon loading the page automatically

I am having trouble getting a pop-up to display whenever an unregistered user tries to access a specific page. I followed an example, but I can't seem to make it work on my page. Any suggestions? Thanks! Image: My code snippet for that page (CSS is ...

Fancybox overlay not adjusting to full height

When working with JavaScript: $(document).ready(function() { $(".fancybox").fancybox({ helpers: { overlay: { opacity: 0.4, css: { 'background-color': '#FFF' ...

Looking for an alternative to cffile for uploading files without using a form submission

Is there a way to upload a file to the server using ajax without submitting the form? I tried using Cffile with the filefield attribute, but since there is no form object passed to coldfusion, it didn't work. I thought of storing the user-entered valu ...

Implementing jQuery to assign values in a Vue.js form

I am facing a dilemma with a large form on an external website that has been developed with Vue.js. Unfortunately, I do not have access to the source code of this website. I am attempting to efficiently update this form in bulk using the browser console. D ...

Utilizing jQuery UI to dynamically alter CSS classes

I'm currently working on a project and could use some assistance. I have divs that are droppable using jQuery UI. While everything is functioning properly and I can drag and drop, I am looking to modify the opacity of the div I am dragging by changing ...

Submitting a form with model data using Ajax in Spring Boot with Thymeleaf

Looking to revamp my spring boot controller by incorporating an ajax endpoint for fetching values from a form with modelAttribute and displaying multiple lists on the page using thymeleaf. Is this achievable? Here is the existing controller: @RequestMappi ...

`Is there a way to quickly incorporate data into an option?`

I am currently working on incorporating dynamic information into an option within a select element. In order to ensure browser compatibility, I would like to utilize data attributes. While attempting to use alt tags, it displayed correctly in Chrome, but t ...

How can I automatically fill a form with data using PHP and jQuery?

function autoFillForm($formData) { //Format: $formData['css_selector'] = "value"; $html = "<script>\n$(document).ready(function(){\n"; foreach($formData as $selector => $value) { $html .= "$('$sele ...