Scott Ledbetter
Scott Ledbetter

Reputation: 338

Making individual jQuery functions more succinct

I'm often tasked with using jQuery for some basic DOM manipulation and end up writing code like this:

$( ".filter-air" ).click(function() {
document.location = "http://url.com" + "?filter=air";
});

$( ".filter-land" ).click(function() {
document.location ="http://url.com" + "?filter=land";
});

$( ".filter-water" ).click(function() {
document.location ="http://url.com" + "?filter=water";
});

...etc

In this example I'm filtering WP posts based on a URL parameter that's appended when clicking different items of a list (each with a unique class).

It seems very verbose, though. How might I accomplish this without writing an individual function for each list item/parameter?

Upvotes: 0

Views: 32

Answers (2)

Roberto LL
Roberto LL

Reputation: 112

You could do something like this

<a href="#" data-filter="air" class="filter">filter-air</a>
<a href="#" data-filter="land" class="filter">filter-land</a>
<a href="#" data-filter="filter-water" class="filter">filter-water</a>

$( ".filter" ).click(function(e) {
  e.preventDefault() // This is to prevent a tag firing
  var filter = $(e.target).data('filter')//<- this gets you the filter from the Data attribute
  console.log("http://url.com?filter=" + filter); //Do your redirect here
});

See working Example here: https://codepen.io/Sensiblemnd/pen/XqgvVO?editors=1111

Upvotes: 0

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92367

You can use following code

function filterClick(name) {
    console.log(name);
    $( ".filter-"+name ).click(function() {
      document.location = "http://url.com" + "?filter="+name;
    });
}

['air', 'land', 'water'].forEach( (name) => { filterClick(name); } )

Upvotes: 1

Related Questions