Blur event triggering first before click event triggers in JavaScript

1.1k views Asked by At

I'm trying to expand the panel in blur event and call some other code in click. But click event is not triggered and only triggering blur event is triggering.

To reproduce, go to the fiddle and type some text on the input box and click test button.

HTML:

<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<div id="accordion">
  <h3>Section 1</h3>

  <div>
      <input type="text" />
    <p>
    Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
    ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
    amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
    odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.
    </p>
  </div>
  <h3>Section 2</h3>
  <div>
    <p>
    Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet
    purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor
    velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In
    suscipit faucibus urna.
    </p>
  </div>
  <h3>Section 3</h3>
  <div>
    <p>
    Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
    Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
    ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
    lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.
    </p>
    <ul>
      <li>List item one</li>
      <li>List item two</li>
      <li>List item three</li>
    </ul>
  </div>
  <h3>Section 4</h3>
  <div>
    <p>
    Cras dictum. Pellentesque habitant morbi tristique senectus et netus
    et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
    faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
    mauris vel est.
    </p>
    <p>
    Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
    inceptos himenaeos.
    </p>
  </div>
</div>

<input type="button" value="test" id="test" />

JavaScript:

  $(function() {

      $( "#accordion" ).accordion();

      $("#test").on("click", function() {
          alert("Click event triggered");
      });

      $("input").on("blur", function() {
          $('#accordion .ui-accordion-content').show();
      });

  });

You can check the JSFiddle here: http://jsfiddle.net/ranjitsachin/zbrntv2r/3/

Note: I found some alternate solution which is not standard way, for example we can use onmousedown instead of click event.

Also, I dont want to call blur event in click event.

1

There are 1 answers

0
STEEL On

Add this before your click event, to stop blur event from happening.

$("#test").on("mouseover", function(evt) {
          evt.preventDefault();
      });