0

How can I activate the click event only on the child of the element (identify by his class) that I clicked?

I try this but seems that active all the onclick event of the .a-collaps-button on the page (I have multiple .collaps-button and multiple .a-collaps-button)

<button class="collaps-button">
  <a href="#adminModal" class="a-collaps-button" data-toggle="modal" onclick="showModalContentjs('modificy')">Modificy</a>
</button>
$('.collaps-button').click(function () {
  $(this).children('.a-collaps-button').click();
});

For the CSS I do this and it works

$(function () {
  $('.collaps-button').hover(function () {
    $(this).children('.a-collaps-button').css('color', '#f44242');
    $(this).children('.a-collaps-button').css('text-decoration', 'none');
  }, function () {
    $(this).children('.a-collaps-button').css('color', 'white');
    $(this).children('.a-collaps-button').css('text-decoration', 'none');
  });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • why use js to style a hover css? Also I don't think an anchor inside a button is valid – Pete Jul 26 '18 at 09:25
  • @Pete I'm going to reopen this as, while that duplicate matches the OPs question, there's a massive flaw in their HTML which renders the point of the question moot. – Rory McCrossan Jul 26 '18 at 09:30

1 Answers1

1

Your major issue is that your HTML is invalid. You cannot nest clickable elements, ie. you cannot place an a element inside a button.

To fix this, remove the a element and simply attach whatever logic you execute on click of that a to the click event of the button instead. Also note that you should not be using outdated on* event attributes. Use unobtrusive event handlers, such as addEventListener() or jQuery's on() or event shortcut methods, such as click().

Also note that you shouldn't use JS to amend the UI. Your hover logic is much more suited to CSS. Try this:

$('.collaps-button').click(function() {
  showModalContentjs('modificy');
});

function showModalContentjs(foo) {
  console.log(foo);
}
.collaps-button {
  color: white;
  text-decoration: none
}
.collaps-button:hover {
  color: #f44242;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="collaps-button">Modificy</button>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339