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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.