IdeoREX
IdeoREX

Reputation: 1485

jQuery in CSS style sheet

I’m working on making my web site fade in and out every time I click a link to another page. I need to use jQuery to do this. Do I need to put the jQuery code on every page or can I write jQuery into the CSS Stylesheet? If so, how do I format the CSS Stylesheet to accept jQuery?

I’m experimenting with the code from this forum post: Fade Out between pages – CSS-Tricks

Edit to question based on comments

So, I now know that I can’t put JavaScript in CSS file. What’s the best way to put JavaScript code that applies to all pages in a site? I want to write this transition code and then not have to write/edit it into every page.

Upvotes: 0

Views: 2102

Answers (2)

Rory O'Kane
Rory O'Kane

Reputation: 30388

Save the JavaScript in a file with the extension .js, for example main.js. Then give it a public URL, in a similar way that your CSS files are accessible from a URL. An example URL: http://example.com/js/main.js. You might do that by putting it in a js folder in your public_html folder on your server – it depends on your server.

Then, near the end of each page’s HTML, right above </body>, add this HTML tag:

<script src="/js/main.js"></script>

The script tag with a src attribute will load the JavaScript at the given URL and then run it immediately.

I recommend putting it at the end of your <body> element and not inside the <head> because the script prevents the rest of the page from loading and displaying to the user while the script runs. If you make the script run only at the very end of the page, the page is already loaded and the user can see all of its content.

Upvotes: 1

you need to do a $.fadeout on the window.beforeunload event, bye

PD: in a js file, not in a stylesheet, you can´t use JS in a stylesheet. bye.

Upvotes: 0

Related Questions