JSFiddle code not working on my own page

I have code that works in JSFiddle , but which I cannot run on my own page.

HTML

<body style="background-color: #000000"> <form oninput="amount.value=range.value" style="color:#1ec2c5;"> <output name="amount" for="range">2</output><a> KM</a> <input type="range" name="range" min="1" max="9" step="1" value="2" id="test"> </body> 

CSS

 input[type="range"]{ -webkit-appearance: none; -moz-apperance: none; border-radius: 6px; width: 225px; height: 6px; border: 2px solid #eceef1; outline:none; background-image: -webkit-gradient( linear, left top, right top, color-stop(0.15, #eceef1), color-stop(0.15, #0c0d17) ); } input[type='range']::-webkit-slider-thumb { -webkit-appearance: none !important; background-color: #1ec2c5; border: 3px solid #000000; height: 25px; width: 25px; border-radius: 20px;} 

Javascript

 $('input[type="range"]').change(function () { var val = ($(this).val() - $(this).attr('min')) / ($(this).attr('max') - $(this).attr('min')); $(this).css('background-image', '-webkit-gradient(linear, left top, right top, ' + 'color-stop(' + val + ', #eceef1), ' + 'color-stop(' + val + ', #0c0d17)' + ')' ); }); 

If I take the code and put in the HTML / JS (linked in the head) / CSS (linked in the head) files, CSS works, but JavaScript doesn't work.

I tried replacing $(this) with the item id, but still no luck.

+7
javascript jquery html css google-chrome
source share
2 answers

"If I take the code and put HTML / JS (linked in the head)"

The problem is that you put your code in <head> , so it runs before the input elements have been parsed, and therefore $('input[type="range"]') does not find the elements.

If you look at the “Frameworks and Extensions” options in the JSFiddle, you will notice that by default the JS code is placed in the onload handler, so your code does not run until the entire page loads. In order for the code to behave the same on your own web page, you need to wrap it in your own onload handler, or - since you are using jQuery - wrap it in a finished document :

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

Or the short form is as follows:

 $(function() { // your code here }); 

Or include your script at the end of the page so that it runs after the elements that it is trying to manipulate have been parsed.

+11
source share

Did you make sure you included the jQuery library in your header? For all types of libraries, check out the Google Developer site. https://developers.google.com/speed/libraries/ Here is the jQuery library you are looking for, be sure to place it in front of your JS file.

  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 

^ This should be in your headline .;)

0
source share

All Articles