The jQuery click event fires the first time, but not the second
This is the HTML I'm working with:
<ul id="categories">
<li><a href="#cargo">Cargo Trailers</a></li>
<div class="dropdown">
<ul>
<li><a href="#utility">Utility Trailers</a></li>
</ul>
</div>
</ul>
I wrote a jQuery script to hide the dropdown div. The dropdown div appears the first time the click event is triggered. As soon as li in the dropdown div is selected and switches places with the first li in #categories ul, clicking li will not result in a dropdown div.
Here is jQuery:
jQuery(document).ready(function($) {
// hide the dropdown div
$('#categories > div').hide();
/*
Click the drop down arrow function
*/
var $listHeader = $('#categories > li');
$listHeader.click(function() {
if ( $('#categories > div:hidden') ) {
//show the drop down
$('#categories > div').show();
} else {
//hide the drop down
$('#categories > div').hide();
}
});
/*
Click a list-item in the drop down function
*/
$('#categories > div a').click(function() {
/* actions to change the title to the newly selected item */
// hide the ul
$('#categories > div').hide();
// move the clicked item to the header
$(this).prependTo('#categories > li');
// move the previous title to the dropdown and sort
$('#categories > li > a:eq(1)').prependTo('#categories > div > ul > li:empty');
// Reset the listHeader variable
$listHeader = $('#categories > li');
// cancel default browser action
return false;
});
});
this $('#categories > div:hidden')one will always return a jQuery object (which evaluates to true), even if there is no matching element selector. Use jQuery .toggle()instead if...else:
$('#categories > div').toggle();
here is an example to play with
: - http://jsfiddle.net/Etkjr/1/
, DOM. , 2 jQuery: .live() .delegate. DOM DOM.
,
$('#categories li:first').live('click', function() {})
, li , li .
$('#categories').delegate('.dropdown a', 'click', functon(evt) {})
.delegate(). , - , .dropdown a #categories, .
.live() , .delegate . , () , delegate .
"" . , .hide() . , , . .live() click() . , li $('.li').live('click', ...) , div.
, .