charlie_cat
charlie_cat

Reputation: 1850

Onclick event needs to click twice?

Why do I have to click twice before the background color is set to green?

This is my JavaScript:

function OnGroupClicked(groupId) {
  var groupIds = new Array();
  $("#group-name-" + groupId).on("click", function () {
    var body = $('#group-name-div' + groupId),
    green = "rgb(0, 128, 0)",
    white = "rgb(255, 255, 255)";

    if (body.css("background-color") !== green) {
      $('#hidden' + groupId).val(1);
      body.css("background-color", green);
    } else {
      $('#hidden' + groupId).val(0);
      body.css("background-color", white);
    }
  });
}

This is my markup:

foreach (var group in Model.AllGroups) {    
    if (Model.GroupsForUser.Any(g => g.GroupId == group.GroupId)) { %>
        <div id="group-name-div<%: group.GroupId %>" style="width:auto; height:50px; border:solid 1px black; margin:5px; background-color:green;" >
            <h3>&nbsp; &nbsp; <a href="javascript:OnGroupClicked(<%: group.GroupId %>)" id="group-name-<%: group.GroupId %>"><%: group.Name %></a></h3> 
        </div>
        <input type="hidden" id="hidden<%: group.GroupId %>" name="group-hidden<%: group.GroupId %>" value="" />
    <% } else { %>
        <div id="group-name-div<%: group.GroupId %>" style="width:auto; height:50px; border:solid 1px black; margin:5px;" >
            <h3>&nbsp; &nbsp; <a href="javascript:OnGroupClicked(<%: group.GroupId %>)" id="group-name-<%: group.GroupId %>"><%: group.Name %></a></h3> 
        </div>
        <input type="hidden" id="hidden<%: group.GroupId %>" name="group-hidden-<%: group.GroupId %>" value="" />
    <% }
} %>

Upvotes: 0

Views: 1366

Answers (1)

Allan Kimmer Jensen
Allan Kimmer Jensen

Reputation: 4389

You are first declaring the event handler on the first click, not firing it.

To explain further, when you click the link you run the OnGroupClicked function, this adds the event listener, but does not fire it.

To get around this, append the event on the element, and use this to know what element was clicked.

You could do something like this:

$(".changeColor").on("click", function () {
 var body = $(this).closest('group-name-div'),
     green = "rgb(0, 128, 0)",
     white = "rgb(255, 255, 255)";

 if (body.css("background-color") !== green) {
   body.next('input').val(1);
   body.css("background-color", green);
 } else {
   body.next('input').val(0);
   body.css("background-color", white);
 }
});

The MVC markup:

<div class="group-name-div" id="group-name-div<%: group.GroupId %>">
  <h3><a href="#" class="changeColor"><%: group.Name %></a></h3> 
</div>
<input type="hidden" id="hidden<%: group.GroupId %>" name="group-hidden<%: group.GroupId %>" value="" />

You don't need the whole function thing.

Upvotes: 2

Related Questions