Pawan
Pawan

Reputation: 32321

How to click First li tag in this case

On Page load i want to make 1D selected as default

I have tried this way

$(document).ready(function() {

$("ul.menu li a:first").click();
});

$("ul.menu li").click(function() {
  var tabclicked = $(this).find("a").attr("href");
  alert(tabclicked);
});

But could you please tell me why the alert is not getting displayed ??

This is my fiddle

https://jsfiddle.net/gr1L23us/3/

Upvotes: 2

Views: 10502

Answers (3)

ahmet2106
ahmet2106

Reputation: 5007

Do it this way: https://jsfiddle.net/gr1L23us/5/

$(document).ready(function() {
  $("ul.menu li a").click(function() {
    var tabclicked = $(this).attr("href");
    alert(tabclicked);
  });

  $("ul.menu li:first-child a").click();
});
  1. change the positions of the event listener function (which is the one with the alert) and then the event
  2. use :first-child as a selector on <li>
  3. change the click event to fire on an <a>

another possible application would be the jquery way: https://jsfiddle.net/gr1L23us/8/

$(document).ready(function() {
  $("ul.menu li a").click(function() {
    var tabclicked = $(this).attr("href");
    alert(tabclicked);
  });

  $("ul.menu li").first().find('a').click();
});

by using the .first() to select the first <li> and .find() to go deeoper on the <a> link inside to fire the click

Upvotes: 5

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

you can trigger click the first li but you should do the trigger after the li click event not before it

$(document).ready(function() {
  $("ul.menu > li").click(function() {
    var tabclicked = $(this).find("a").attr("href");
    alert(tabclicked);
  });
  $("ul.menu > li:first").trigger('click');
});

Working Demo

Upvotes: 3

j08691
j08691

Reputation: 207861

Put your click function within the document ready call, before $("ul.menu li a:first").click();.

$(document).ready(function() {
  $("ul.menu li").click(function() {
    var tabclicked = $(this).find("a").attr("href");
    alert(tabclicked);
  });
  $("ul.menu li a:first").click();
});

jsFiddle example

Upvotes: 1

Related Questions