Jump to content

jQuery click();


The Little Guy

Recommended Posts

I have this function:

function toggleEdit(){
$(".editNavLeft").each(function(){
	$(this).removeClass('editClicked');
	$(this).click(function(){
		$(this).addClass("editClicked");
	});
});
}

 

It removes "editClicked" class from all the "editNavLeft" divs then adds editClicked to the clicked div. The problem is that this doesn't work on the first click. The second click on the same or different nav item works fine.

 

The Nav:

<?php
echo '
<div class="lnav alignLeft">
	<ul>
		<li><a class="editNavLeft editClicked" onclick="toggleEdit(\'basics\');" href="javascript:void(0);">Basics</a></li>
		<li><a class="editNavLeft" onclick="toggleEdit(\'appearance\');" href="javascript:void(0);">Appearance</a></li>
		<li><a class="editNavLeft" onclick="toggleEdit(\'interests\');" href="javascript:void(0);">Interests</a></li>
		<li><a class="editNavLeft" onclick="toggleEdit(\'lifestyle\');" href="javascript:void(0);">Lifestyle</a></li>
		<li><a class="editNavLeft" onclick="toggleEdit(\'mate\');" href="javascript:void(0);">My Mate</a></li>
		<li><a class="editNavLeft" onclick="toggleEdit(\'likes\');" href="javascript:void(0);">Turn Ons</a></li>
		<li><a class="editNavLeft" onclick="toggleEdit(\'dislikes\');" href="javascript:void(0);">Turn Offs</a></li>
	</ul>
</div>';
?>

 

What is wrong with the jQquery?

Link to comment
https://forums.phpfreaks.com/topic/234728-jquery-click/
Share on other sites

The problem is that this doesn't work on the first click.

 

This is because your using an onClick event within your markup to register a click event through jQuery. In other words, your toggleEdit function is only executed when you click an item, this then attaches click events to the rest of the items and waits for the next click.

 

onClick() events and mixing Javascript amongst your markup are a thing of the past since jQuery and other frameworks now allow you to easily attach events to code without them.

 

This concept should be covered in any 'beginner' jQuery tutorials. It really is one of the fundamentals of the framework.

Link to comment
https://forums.phpfreaks.com/topic/234728-jquery-click/#findComment-1206269
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.