Andre Helberg
Andre Helberg

Reputation: 551

Execute JS before CSS

I have the following html file:

<!DOCTYPE html>
<html>
<head>
<link href="example.css" rel="stylesheet">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>

<form class="search">
    <div class="search_box">
         <input type="text" name="q" id="search_text" placeholder="Search..." />
             <ul id="search_results" class="results" >
                 <li><a href="">Search Result #1<br /><span>Description...</span></a></li>
                 <li><a href="">Search Result #2<br /><span>Description...</span></a></li>
             </ul>
    </div>
</form>
   <script type="text/javascript">
        $(document).on('click', '#search_results li',function(i) {
              i.preventDefault();
              console.log('clicked');
          });
    </script>

</body>
</html>

and the css looks like this:

.search .search_box input:focus +  .results { visibility: visible }

.search .search_box .results {
    visibility:hidden;
}

If the css is not included the document works as expected and prints "clicked" when clicking on one of the anchor tags, but not when including the css.

So I suspect the item is hidden before the javascript is executed. I really like the css solution more than having hide and toggle javascript statements.

Is there a method to fix this?

Upvotes: 1

Views: 871

Answers (4)

epascarello
epascarello

Reputation: 207511

Add a hover state to keep the items visible.

.search .search_box input +  .results:hover,
.search .search_box input:focus +  .results { visibility: visible }

.search .search_box .results {
    visibility:hidden;
}

Working fiddle for the downvoters: http://jsfiddle.net/cEP95/

Upvotes: 2

Paul Rad
Paul Rad

Reputation: 4882

In response to "Execute JS before CSS", the only road consists to load the css stylesheet once the dom is ready. So, you can try something like:

Somewhere in your section:

<style type="text/css">
body { display: none }
</style>

JS:

 $(function() {
     $('head').append('<link type="text/css" rel="stylesheet" href="example.css" />');
 });

In the css:

body { display: block }

Upvotes: -2

j08691
j08691

Reputation: 207901

Change click() to mousedown(). The click event includes a mouse up to register, and by that time the focus has been lost.

$(document).on('mousedown', '#search_results li', function (i) {
    i.preventDefault();
    console.log('clicked');
});

jsFiddle example

Upvotes: 6

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

Try using opacity:0 and opacity:1 instead of visibility:hidden and visibility:visible respectively.

This is because the order of events when you click is:

  • Blur the previous element - this causes :hover to no longer apply
  • Click on the new element... but it's hidden now!

Upvotes: 3

Related Questions