0

In my menu, I have these items:

<ul>
    <li class="menu_item" data-content_id="#landscape_context">Landscape Context</li>
    <li class="menu_item" data-content_id="#terrestrial_features">Terrestrial Features</li>
    <li class="menu_item" data-content_id="#aquatic_features">Aquatic Features</li>
    <li class="menu_item" data-content_id="#vegetaion_land_use">Vegetation/Land Use</li>
    <li class="menu_item" data-content_id="#additional_features">Additional Features</li>
    <li class="menu_item" data-content_id="#data_descriptions">Data Descriptions</li>
    <li class="menu_item" data-content_id="#faq">FAQ</li>
</ul>

Then when a user clicks on one of the items, I want to show the content for that data-content_id. However, nothing is happening when I click.

Here is the javascript:

$(".menu_item").click(function () {
    alert("Hello");
}); 

I've replaced the code with the simple alert which also does not show up when I click on a menu item.

I've looked at numerous of the other examples found here on SO, but couldn't find anything different about my solution.

Anybody see what I might be doing wrong here?

Thanks

6
  • 3
    Put it in a DOM ready event handler. Commented Jan 8, 2013 at 16:27
  • 2
    Make sure it's wrapped in $(document).ready(function() {...}); so that it executes after the DOM has loaded and the elements exist. Take a look at this page of the documentation for more information. Commented Jan 8, 2013 at 16:27
  • 1
    Have you placed your code in a $(document).ready(function() { .. }); block? Are the li elements dynamically appended? Commented Jan 8, 2013 at 16:28
  • 1
    Ah, yes, I moved it to my .ready() and now it works! Thanks. :) Commented Jan 8, 2013 at 16:28
  • 1
    @Pow-Ian The .live() function has been deprecated since version 1.7. Using that instead of simple jQuery practices makes no sense. Commented Jan 8, 2013 at 16:30

3 Answers 3

2
$(document).ready(function(){
   $(".menu_item").click(function () {
       alert(  $(this).attr("data-content_id") );
   }); 
}); 
Sign up to request clarification or add additional context in comments.

1 Comment

@Explosion Pills thanks for the identation...still struggling with the editor :D
0

Either the elements are loaded in the DOM after your script or they are loaded asynchronously. If it's the former, just wrap everything in $(document).ready(function () {... (or $(function () {...

If it's the latter, use event delegation, such as:

$(document).on('click', '.menu_item', function () {

Comments

0

Try this code :

$(document).ready(function() {
   $(".menu_item").click(function () {
       alert($(this).attr("data-content_id"));
   }); 
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.