currentlyOffline

Get element ID in jQuery

February 1st, 2009 currentlyOffline

A very small tip for people who are new with jQuery.

let’s say you have a list of images, with the same class, something like:


   1:<img src="somethinghere1" alt="alt1" title="title1" class="someClass" />
   2:<img src="somethinghere2" alt="alt2" title="title2" class="someClass" />
   3:<img src="somethinghere3" alt="alt3" title="title3" class="someClass" />
   4:<img src="somethinghere4" alt="alt4" title="title4" class="someClass" />

I’m not going into more detail on this straightforward code. If you’re unsure why I’m using both title and alt on image, feel free to ask any SEO person ;)

So, anyway, you want some action when user moves mouse over each image. Let’s say you want to add 75 pixels of solid pink border around the image(hope you’re not…). I know you expect something very simple like this.css(“border”, “75px solid pink”). Unfortunately that won’t work for you :(

But there’s a quite simple solution if you know that you can get id of current element and it’s stored in this.id

So add id’s to your elements:

   1:<img src="somethinghere1" id="img1" alt="alt1" title="title1" class="someClass" />
   2:<img src="somethinghere2" id="img2" alt="alt2" title="title2" class="someClass" />
   3:<img src="somethinghere3" id="img3" alt="alt3" title="title3" class="someClass" />
   4:<img src="somethinghere4" id="img4" alt="alt4" title="title4" class="someClass" />

And now it’s easy:

   1:$(".someClass").mouseover(function(){
   2:                $("#" + this.id).css("border","75px solid pink");
   3:});

Here we are – you solved this annoying problem, so you can switch you computer off, call you best mates and go for a beer. Computers are bad for you!

Posted in jQuery | No Comments »

  • You are currently browsing the currentlyOffline weblog archives for February, 2009.

  • Pages

    • About
  • Archives

    • December 2009
    • November 2009
    • September 2009
    • August 2009
    • July 2009
    • June 2009
    • May 2009
    • April 2009
    • February 2009
    • January 2009
    • November 2008
  • Categories

    • books (3)
    • Cristina Scabbia (1)
    • I hate computers… and Internet! (6)
    • Jokes (1)
    • jQuery (1)
    • Music (1)
      • italian metal (1)
      • Lacuna Coil (1)
    • Question – Answer (1)
    • randomness (3)
    • Uncategorized (2)
    • web hosting jokes (3)
    • Zend Framework (6)

currentlyOffline is proudly powered by WordPress | Bob