Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery check element ID

Tags:

jquery

I know there is plugin called .hasClass();

I have the following

$('#page_background, #header_background').ColorPicker({...

how would I check if page_background is clicked and not header_background?

This is what I have now, it won't work.

$('#page_background, #header_background').ColorPicker({
        onSubmit: function(hsb, hex, rgb, el) {
            $(el).val(hex);
            $(el).ColorPickerHide();

            var id = this.id;

            if(id == 'page_background')
                $('body').css("background-color","#"+hex);
        },
        onBeforeShow: function () {
            $(this).ColorPickerSetColor(this.value);
        }
    })
    .bind('keyup', function(){
        $(this).ColorPickerSetColor(this.value);
    });
like image 280
Grigor Avatar asked Jun 04 '12 17:06

Grigor


2 Answers

$(function(){
   $('#page_background, #header_background').click(function(){

   var id = this.id;
   if(id == 'page_background')
     // page background
   else
     //header 
 });
});

Working fiddle

As you are using this inside colorpicker onSubmit function

onSubmit: function(hsb, hex, rgb, el) {

where you get the element as el, so to get the id use

 var id = $(el).attr('id');
 // or
 var id = $(el).prop('id'); // new way
 //or simply
 var id = el.id; // this should work too
like image 123
Prasenjit Kumar Nag Avatar answered Oct 21 '22 12:10

Prasenjit Kumar Nag


Assuming you have a reference to the clicked element stored in this, you can simply use the native DOM property:

var id = this.id;

If this is a jQuery object, not a DOM node, you can use this.attr("id").

Also note that hasClass is a normal jQuery method, not a plugin. It's part of the standard jQuery library.

like image 21
James Allardice Avatar answered Oct 21 '22 13:10

James Allardice