d4ne d4ne - 5 months ago 17
jQuery Question

JS/Jquery get clicked id

I'm trying to get the id from an clicked a element using jquery.

For example a user clicks on a

<a></a>
element I want the ID to store inside a variable. I know how to manage this using
<select></select>
elements but got no clue how to manage this using a simple menu containing a links.

Preview:

preview

Source code:

<div class="list-group no-border mb-5">
<a id="background" class="list-group-item"><i class="icon-bucket"></i> Profile Background</a>
<a id="boxes" class="list-group-item"><i class="icon-cube"></i> Profile Boxes</a>
<a id="fonts" class="list-group-item"><i class="icon-font"></i> Profile Fonts</a>
<a id="highlights" class="list-group-item"><i class="icon-stack-empty"></i> Profile Highlights</a>
<a id="content" class="list-group-item"><i class="icon-markup"></i> Profile Content</a>
<a id="media" class="list-group-item"><i class="icon-video-camera2"></i> Profile Media</a>
</div>


Does anyone have a idea?

Answer

There are a variety of ways that you could resolve the ID of which element was clicked since you are using jQuery. You'll just need to ensure that you have a variable defined in the proper scope (i.e. outside of your click event) :

<script>
    // Example variable
    var clickedId;
    // jQuery code here
</script>

Then define a click event handler to pick up any click events and set your variable using either this.id or $(this).attr('id'), which will both return the ID attribute of the element clicked (i.e. this) :

<script>
    // Example variable
    var clickedId;
    $(function(){
         // When any link is clicked
         $('a').click(function(){
              // Set your variable
              clickedId = this.id; // or clickedId = $(this).attr('id');
         });
    });
</script>

Example

enter image description here

// Example variable
var clickedId;
$(function(){
   // When any link is clicked
   $('a').click(function(){
         // Set your variable
         clickedId = this.id; // or clickedId = $(this).attr('id');
         console.log(clickedId + ' was stored in clickedId');
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-group no-border mb-5">
    <a id="background" class="list-group-item"><i class="icon-bucket"></i> Profile Background</a>
    <br />
    <a id="boxes" class="list-group-item"><i class="icon-cube"></i> Profile Boxes</a>
  <br />
    <a id="fonts" class="list-group-item"><i class="icon-font"></i> Profile Fonts</a>
  <br />
    <a id="highlights" class="list-group-item"><i class="icon-stack-empty"></i> Profile Highlights</a>
  <br />
    <a id="content" class="list-group-item"><i class="icon-markup"></i> Profile Content</a>
  <br />
    <a id="media" class="list-group-item"><i class="icon-video-camera2"></i> Profile Media</a>
</div>