Naterade
Naterade

Reputation: 2675

The best way to hide a DOM element using JQuery without multiple .hide() calls

So my site uses the Google Maps API to display a map of the company hosting the deal once the user clicks to view the deal itself. If the map function returns true I user $('#map').show() to display it.

I know I can use the .hide() when the user clicks another button on the page to hide the div, but I have about 7 buttons on the page that do different things and using $('#map').hide() in each one is doable but seems repetitive and ugly coding wise.

Does anyone have any suggestions as to hide the div when a user clicks on any other button besides the 'view deal' button, maybe some form of .each() ?

Upvotes: 0

Views: 336

Answers (4)

jfriend00
jfriend00

Reputation: 707396

Make a single javascript function that handles setting your view. Have each button call that function by just passing in the view they want. Then, in only one place in your code (in that function), you can handle preparing the page for the new view. This allows all your code to by much more DRY than having completely separate code for each button.

For some reason, the design pattern common with jQuery event handlers (declaring anonymous functions) tends to make people think they have to have separately written code in each event handler rather than calling a shared function from the event handler that does most or all of the work for all your buttons in just one place.

Upvotes: 0

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34160

you can use toggle instead of show button:

$("#map").toggle();

if it is being shown it will hide, and if it is hidden it will be shown.

Upvotes: 1

David Hedlund
David Hedlund

Reputation: 129792

You could have a handler for all buttons, that manages just the map visibility, and then other handlers for the more specific stuff:

$('.button').click(function() {
    $('#map').toggle($(this).is('#the-map-button'));
});

$('#specific-button').click(function() {
    // specific stuff
    // map visibility will be taken care of elsewhere
});

Upvotes: 1

Till
Till

Reputation: 22408

I'm hoping your buttons share the same CSS:

$('.button').click(function(){
    $('#map').hide();
});

Upvotes: 1

Related Questions