jQuery: How to bind the same action on two different events? -


i find myself writing code looks this:

$(document).ready(function(){      updatestuff();      $('select').change(function(){         updatestuff();     }); });  function updatestuff(){     //do simple } 

the same function updatestuff() called twice (once each event), nothing different between 2 events. wondering if there better way write same code called on both events, , can dry code more. way, won't need create function in first place.

maybe (if such syntax exists)?

$('select').bind(['document.ready', 'change'], function(){     //do simple }); 

you need have change event binding inside of ready handler, dom guaranteed ready manipulation when binding. doing in simplest possible way can think of. change code bind change event so:

$('select').change(updatestuff); 

unless need pass in parameters, there's no need wrap call updatestuff() in anonymous function.

as jandy points out, can invoke function you've bound event handler manually invoking event's handlers jquery, so:

$('select').change(updatestuff).change(); 

you using shorthand ready binding, code simplified down this:

$(function(){     $('select').change(updatestuff).change(); });  function updatestuff(){     //do simple } 

however, if wanted bind other events (other ready) @ same time, so:

$('select').bind('change click', updatestuff); 

have @ documentation .bind() here


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -