How to put codes from jsfiddle.net on my website?

I tried to create a small box at the bottom of my web page that will expand / pop up when scrolling and then close again when the mouse leaves.

I found this post with a link to jsfiddle.net (which I did) and created something that works exactly the way I want it when you look at JSFiddle. But I can't get it to work when I open it on my website (I think it may have something to do with setting onLoad , but Im really not sure).

This is what I created in JSFiddle:

Javascript

 $('#box').hover(function() { $(this).animate({ height: '220px' }, 150); }, function() { $(this).animate({ height: '20px' }, 500); }); 

CSS

 #box { position: absolute; width: 300px; height: 20px; left: 33%; right: 33%; min-width: 32%; bottom: 0; background-color: #000000; } 

HTML

 <div id="box"></div> 

This works fine in JSFiddle, but not when I try to embed code in my files and link them together. If I changed the drop-down list in JSFiddle from onLoad or onDomReady to anything else, it will stop working, but the code will not change. So I think I should add something else for this.

As you probably guessed, I'm a complete newbie when it comes to JavaScript, so I'm sure Im not doing something right.

Can someone tell me how to save JavaScript code and link it to my webpage so that it works exactly the same as on JSFiddle?

+4
source share
1 answer

You run this code immediately, rather than waiting for the DOM to be ready. This means that the #box element may not yet exist.

jsFiddle automates this process to make your code cleaner. You need to do this yourself when you post the code on your own website. It is very simple: you just need to put your code in the ready event callback on document :

 $(document).ready(function() { // put your Javascript here }); 

or, shortened version:

 $(function(){ // put your Javascript here }); 

They are semantically and functionally equivalent.

+4
source

Source: https://habr.com/ru/post/1338911/


All Articles