Search code examples
javascripthtmlcssjsphref

Apply on click javascript event to a header in JSP instead of using <a> tag


I currently have a header with a toggle button which will expand on click.

Html :

<h3 class="toggle_header" id="Tax_information_eSignature">
    <a href="javascript:void(0);" class="icon_toggle_open"></a>
    <spring:message code="TaxInformation.eSignature" />
    <label for="Tax_information_eSignature"></label>
</h3>

JS:

$(document).on('click', '.icon_toggle_open', function (e) {
        stop(e);
        $(this).removeClass("icon_toggle_open")
            .addClass("icon_toggle_close")
            .attr("alt","Show")
            .attr("title","Show")
            .parent().next('.toggle_content').hide();
        $(window).blur();       
      });

     $(document).on('click', '.icon_toggle_close', function (e) {
        stop(e);
        $(this).removeClass("icon_toggle_close")
            .addClass("icon_toggle_open")
            .attr("alt","Hide")
            .attr("title","Hide")
            .parent().next('.toggle_content').show();
        $(window).blur();       
      });

It is currently working as expected. The user needs to click on the toggle icon to expand the div. enter image description here

Instead of clicking on the expand button, I want the Expand/collapse to be triggered upon clicking anywhere in the accordion bar. I am new to JSP, can anyone help?


Solution

  • You want to set the event listener higher in the DOM. Try moving your event listener from .icon_toggle_open to .toggle_header.

    $(document).on('click', '.toggle_header', function (e) {
      stop(e);
      var opened = $(this).children('.icon_toggle_open')
      if(opened.length > 0){
        opened
          .removeClass("icon_toggle_open")
          .addClass("icon_toggle_close")
          .attr("alt","Show")
          .attr("title","Show")
          .parent().next('.toggle_content').hide();
      } else {
        $(this)
          .children(".icon_toggle_close")
          .removeClass("icon_toggle_close")
          .addClass("icon_toggle_open")
          .attr("alt","Hide")
          .attr("title","Hide")
          .parent().next('.toggle_content').show();
      }
      $(window).blur(); 
    });