Removing Redundant Repetition - J Query

You need to hide, show, or otherwise manipulate some DOM elements when the page loads, and you also need to take the same actions later in response to a couple of different events:

The code is working, but you want to simplify it so there’s not so much duplicate code.

Solution 1

Move the duplicate code into a function, and call the function both at load time and in response to the event. Use jQuery’s.bind() method to wire up both event handlers at the same time. And save data used more than once in variables:

Solution 2

Use jQuery’s event triggering to fire the event immediately after attaching it, along with the.bind() trick and local variables from solution 1:

It’s standard programming practice in just about any language to take duplicate code and move it into a separate function that can be called from multiple places. Solution 1 follows this approach: instead of repeating the code to set the visibility, it appears once in the setVisibility() function. The code then calls that function directly at startup and indirectly when the change event is fired.
Solution 2 also uses a common function for both of these cases. But instead of giving the function a name so it can be called directly at startup, the code merely sets the function as the event handler for the change event and then uses the trigger() method to trigger that same event—thus calling the function indirectly. These approaches are more or less interchangeable; it’s largely a matter of taste which you prefer.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics