Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create own function in JQuery?

Tags:

jquery

how to create own function and call it another function? like-

$('.mycls li').hover(function() {    
var divid = $(this).find('li').attr('some_attr');
call myfunc(divid);
});

function myfunc(divid)
{
$(divid).show();
//I want to hide rest all divs 
$('div#info1').hide();
$('div#info2').hide();
$('div#info3').hide();
}

I have 2 questions one is how to implement this logic in jquery second is which attribute can be used to reference the specific li to specific div

my divs are as-

<div id="info1">
//some information
</div>
<div id="info2">
</div>
....
like image 912
nectar Avatar asked Jun 03 '26 10:06

nectar


2 Answers

Your functions should be able to operate on the wrapped set like other methods/functions of jquery. Consider a plugin, it is easy:

jQuery Plugin Tutorial

Or see:

Defining your own functions in jQuery

like image 134
Sarfraz Avatar answered Jun 06 '26 00:06

Sarfraz


I wrote this:

jQuery.fn.doSomeStuff = function(options, callback) {
    var $elem = $(this[0]);
    var args = options || {};
    
    // doSomeStuff
    alert("DOM element: "+$elem.html());
    alert("this ia a parameter:"+ args.aParameter);
    
    if (typeof callback == 'function') { // make sure the callback is a function
        callback.call(this); // brings the scope to the callback
    }
    return $elem; //ensures jquery chainability
};
  1. define your own function
  2. specify parameters and callback
  3. ensure jquery chainability

You can try it here

like image 45
Marco Allori Avatar answered Jun 06 '26 01:06

Marco Allori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!