Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selector passing to jQuery function

I have a function in which I want the selector that I am passing to do the enclosed processes. The functions are listed below:

function menuselector (id){
    $(id).css('background', 'url(../img/black_denim.png) repeat');
    $(id).css('color', '#FFF');

}
function menudeselector (id){
    $(id).css('background', 'none');
    $(id).css('color', '#CE0101');

}

menuselector('mgi');

mgi is an ID of a div tag

like image 737
Asim Naseer Avatar asked Sep 01 '26 18:09

Asim Naseer


2 Answers

Ids are targeted by using a hash before the id, the same as in CSS.

If you're passing

menuselector('mgi');

You will need to adjust it to make it a valid selector.

$('#' + id).css(...

or you can send the valid selector

menuselector('#mgi');

assuming you have an element with that id (you haven't shown that)

<div id="mgi">

Aside

You shouldn't keep selecting the element. You can either chain

$(id).css('background', 'none').css('color', '#CE0101');

// on new lines for readability if there are a lot of actions
$(id).css('background', 'none')
    .css('color', '#CE0101');

or use an object

$(id).css({background: 'none', color: '#CE0101'});
like image 184
Popnoodles Avatar answered Sep 04 '26 08:09

Popnoodles


mgi is not a valid selector. You should write:

menusector('#mgi');

or

menuselector('.mgi');

depending on whether you want to select an ID or a class.

You could use popnoodle's solution, if your function should only be applicable to IDs, although making it restrictive like that seems like poor generality.

like image 40
Barmar Avatar answered Sep 04 '26 06:09

Barmar



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!