-1

I have created a function for a sidebar that slides down the first href when clicking on this and then anything that was not this would slide up. This worked fine until I needed to call the function using "onclick" which then meant not $(this) would not work as it can only call (this) . I am using tagbuilder so can only call one unique event listener.

JS

$(".foo > a").each(function () {
    $(this).click(function () {
        $(this).siblings(".sibling").slideToggle();
        $(this).toggleClass("active");

        $(".foo > a").not(this).siblings(".sibling").slideUp();
        $(".foo > a").not(this).removeClass("active");

    });
});

C#

a.MergeAttribute("onclick", "Click.call(this)");

Not this to target the sidebar and slide not this up

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
  • *I needed to call the function using "onclick"* - why? it looks like it should work fine using jquery event handler. Why would you (also?) need `onclick=`? Remove the `onclick=` and it should work ok. – freedomn-m Jun 12 '19 at 16:07
  • The fix is to move your inline anonymous event handler out into its own named function and then call `onclick="eventhandler(this)"` *and* `$(".foo>a").click(eventhandler)` – freedomn-m Jun 12 '19 at 16:08
  • I need to call it onclick as the project is using partials and the event handlers in the function don't always work properly due to being called on $(window).load. Where as onclick takes care of all the possible errors – Sean Pelser Jun 12 '19 at 16:12
  • 1
    To get around the issue of the elements not existing because they are loaded via partials, you can use event delegation: `$(document).on("click", ".foo>a", function() { ... });` : more info: https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – freedomn-m Jun 12 '19 at 16:23
  • This is a classic XY Problem - you need to X (bind event to dynamically loaded elements) so you've tried to do this by Y (onclick=) and asked about Y rather than asking about X. – freedomn-m Jun 12 '19 at 16:45
  • Okay thank you, appreciate the help :) – Sean Pelser Jun 13 '19 at 07:58

1 Answers1

1

To not add CSS class to the current target, just remove the current CSS and add to its siblings.

$(".foo > a").click(function () {
  $(this)
    .removeClass('active')
    .siblings()
    .addClass('active');
});
.foo {
  display: flex;
}

.foo a {
  border: 1px solid black;
  color: black;
  padding: 15px;
  margin: 15px;
  text-decoration: none;
}

.foo a.active {
  background: black;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foo">
  <a href="#">Link1</a>
  <a href="#">Link2</a>
  <a href="#">Link3</a>
</div>
Toxnyc
  • 1,350
  • 7
  • 20