Related
I have a click event handler for an anchor that grabs the selector's ID as a variable, has an if parameter and runs 2 functions with return false; at the end to prevent the window from refreshing:
function ItemNumberHistory(ItemNumber) {
var state = {ItemNumberHistory: ItemNumber};
var title = null;
var path = '/Inventory/' + ItemNumber;
history.pushState(state, title, path); // Add item number to URL/history
}
$(document).on('click', '.StoneLink', function(event) {
var ItemNumber = $(this).attr('id'); // Get item number from ID;
// Toggle nav on mobile
if($(navContent).is(':visible')) {
$(navContent).addClass('navHide'); // Hide nav on mobile
$('#navToggleIcon').toggleClass('mdi-close mdi-menu'); // Toggle nav menu icon
}
ItemNumberHistory(ItemNumber);
loadItem(ItemNumber);
return false;
});
For some reason though this still refreshes the window [although return false; is expected to prevent that], but when I comment out ItemNumberHistory(ItemNumber); (line 23) the return false; doesn't refresh the window.
return false; doesn't work when I delete the contents of ItemNumberHistory(ItemNumber); either. It seems that i'm having the issue simply because the function is inside the click event handler.
How do I run my click event handler without the window refreshing on click?!
CODE SNIPPET
var ItemNumberHistory = '';
function loadItem(ItemNumber) {
ItemNumberHistory = ItemNumber;
$('#pageRoot').css('overflow-y', 'hidden');
$('.LoadItem, #StonePage').show(); // Show modal and loader
$.ajax({
url: 'vendors/pages/Inventory/LandingPage/Item.php?number=' + ItemNumber,
method: 'POST',
data: {ItemNumber: ItemNumber},
async: true,
cache: false,
error:
function(jqXHR, strError) {
if(strError == 'timeout') {
// Do something. Try again perhaps?
alert('Seems like there was an error loading this stones information.');
}
},
success:
function(data) {
$('#StoneDetails').html(data);
},
timeout: 3000
});
}
function ItemNumberHistory(ItemNumber) {
var state = {ItemNumberHistory: ItemNumber};
var title = null;
var path = '/Inventory/' + ItemNumber;
history.replaceState(state, title, path); // Add item number to URL/history
}
$(document).on('click', '.StoneLink', function(event) {
var ItemNumber = $(this).attr('id'); // Get item number from ID;
// Toggle nav on mobile
if($(navContent).is(':visible')) {
$(navContent).addClass('navHide'); // Hide nav on mobile
$('#navToggleIcon').toggleClass('mdi-close mdi-menu'); // Toggle nav menu icon
}
ItemNumberHistory(ItemNumber);
loadItem(ItemNumber);
return false;
});
function closeModal() {
if($('#StonePage').is(':visible')) {
$('#StonePage').hide();
$('#pageRoot').css('overflow-y', 'auto');
history.replaceState(null, null, '/Inventory'); // Remove ItemNumber from URL path
}
}
// Hide modal when close button
$(document).on('click', '#CloseModal', function() {
closeModal();
});
// Hide modal on click away
$(document).on('click', '.head, #StonePage', function(event) {
// If clicked anywhere [on #StonePage] outside of .modal
if(!$('.modal').is(event.target) && $('.modal').has(event.target).length === 0) {
closeModal();
}
});
// Hide modal on esc key press
$(document).on('keydown', function(event) {
// keyCode 27 is esc key
if(event.keyCode == 27) {
closeModal();
}
});
.modalContainer {
display: none;
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
padding: 0;
margin: 130px 0 0 0;
overflow: auto;
z-index: 2;
cursor: pointer;
outline: none;
background-color: rgba(0, 0, 0, .25);
}
.modal {
width: 700px;
height: 375px;
padding: 0;
margin: 20px auto;
box-shadow: 0 0 10px #000;
-webkit-box-shadow: 0 0 10px #000;
-moz-box-shadow: 0 0 10px #000;
-o-box-shadow: 0 0 10px #000;
-ms-box-shadow: 0 0 10px #000;
cursor: default;
background-color: #fff;
}
.StoneDetails {
}
/* .CloseModal height and width are 36px */
.CloseModal {
position: relative;
float: right;
color: #ff0000;
text-align: right;
cursor: pointer;
user-select: none; /* Standard syntax */
-webkit-user-select: none; /* Safari 3.1+ */
-moz-user-select: none; /* Firefox 2+ */
-ms-user-select: none; /* IE 10+ */
z-index: 9;
background-color: transparent;
}
.CloseModal:hover {
text-shadow: 1px 1px 10px rgba(150, 150, 150, 1);
}
.CloseModal:active {
color: #000;
}
/* Load Item */
.LoadItem {
display: none;
position: absolute;
width: 700px;
height: 375px;
margin: auto;
padding-top: 164px;
user-select: none; /* Standard syntax */
-webkit-user-select: none; /* Safari 3.1+ */
-moz-user-select: none; /* Firefox 2+ */
-ms-user-select: none; /* IE 10+ */
overflow: hidden;
z-index: 4;
border: 0px solid red;
background-color: #fff;
}
.noScroll {
position: fixed;
overflow-y: scroll;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Inventory">
<div id="StonePage" class="modalContainer" tabindex="0">
<div class="modal">
<div id="CloseModal" class="CloseModal" title="Close">
<span class="mdi mdi-36px mdi-close"></span>
</div>
<div id="StoneDetails" class="StoneDetails">
<!-- Content appends here -->
</div>
</div>
</div>
<div class="InventoryContent">
<!-- Stone listings -->
<div id="StoneContainer">
<div class="Stone" id="StoneIteration" data-listing="1" data-totalrows="1">
<!-- Stone's landing page -->
<a href="<?php $_SERVER['DOCUMENT_ROOT'] ?>/Inventory/Item Number" class="StoneLink" id="Item Number">
<!-- Image -->
<div class="StoneData StoneIMG">
<img src="image.jpg">
</div>
<!-- Weight -->
<div class="StoneData">
Weight
</div>
<!-- Type -->
<div class="StoneData">
Type
</div>
<!-- Enhancement -->
<div class="StoneData">
Enhancement
</div>
<!-- Dimensions -->
<div class="StoneData">
Dimensions
</div>
<!-- Item Number -->
<div class="StoneData">
#Item Number
</div>
</a>
</div>
</div>
</div>
</div>
I'm not sure if this is what you want.
'a href' is suspected.
change your tag
<a href="javascript:void(0);" class="StoneLink" id="<?php echo $row['number']; ?>">
(or <a href="#" class="StoneLink" id="<?php echo $row['number']; ?>">)
and change your event function
$('.StoneLink').on('click', function(event) {
var ItemNumber = $(this).attr('id'); // Get item number from ID;
// Toggle nav on mobile
if($(navContent).is(':visible')) {
$(navContent).addClass('navHide'); // Hide nav on mobile
$('#navToggleIcon').toggleClass('mdi-close mdi-menu'); // Toggle nav menu icon
}
ItemNumberHistory(ItemNumber);
loadItem(ItemNumber);
location.href = '/Inventory/'+ItemNumber; // '<a href="">' instead
return false;
});
I went through the code you posted and there are a bunch of small, semantic issues (not the culprit here though). I was able to run most of it successfully on my local machine. A couple things:
Make sure you're stopping propagation correctly i.e. event.preventDefault(), not event.preventDefault.
navContent isn't defined (at least within the snippet provided).
Do you need ItemNumberHistory both as a variable and function definition? It's confusing.
I think if you add this you'll be fine:
$('.StoneLink').on('click', function(event) {
event.preventDefault();
var ItemNumber = $(this).attr('id'); // Get item number from ID;
// Toggle nav on mobile
if($(navContent).is(':visible')) {
$(navContent).addClass('navHide'); // Hide nav on mobile
$('#navToggleIcon').toggleClass('mdi-close mdi-menu'); // Toggle nav menu icon
}
ItemNumberHistory(ItemNumber);
loadItem(ItemNumber);
location.href = '/Inventory/'+ItemNumber; // '<a href="">' instead
return false;
});
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have prepared a complete example for my question -
Screenshot with a div and 3 jQuery UI sliders:
HTML code:
<div id="myCanvas"></div>
<p>Select background color:
<span id="swatch"></span>
<div id="red"></div>
<div id="green"></div>
<div id="blue"></div>
</p>
CSS code:
#myCanvas {
background: radial-gradient(#FFFFFF, #99CC99);
width: 300px;
height: 60px;
}
#red,
#green,
#blue {
width: 300px;
margin: 15px;
}
#swatch {
padding: 10px;
margin: 5px;
color: #FFF;
}
#red .ui-slider-range {
background: #ef2929;
}
#red .ui-slider-handle {
border-color: #ef2929;
}
#green .ui-slider-range {
background: #8ae234;
}
#green .ui-slider-handle {
border-color: #8ae234;
}
#blue .ui-slider-range {
background: #729fcf;
}
#blue .ui-slider-handle {
border-color: #729fcf;
}
JavaScript code:
jQuery(document).ready(function($) {
$('#selectable').selectable();
$('#kukuSlider').slider();
function hexFromRGB(r, g, b) {
var hex = [
r.toString(16),
g.toString(16),
b.toString(16)
];
$.each(hex, function(nr, val) {
if (val.length === 1) {
hex[nr] = '0' + val;
}
});
return hex.join('').toUpperCase();
}
function refreshSwatch() {
var red = $('#red').slider('value'),
green = $('#green').slider('value'),
blue = $('#blue').slider('value'),
hex = '#' + hexFromRGB(red, green, blue);
$('#swatch').text(hex);
$('#swatch').css('background-color', hex);
// why does not the following line work?
$('#myCanvas').css('background', 'radial-gradient(#FFFFFF, ' + hex + ');');
console.log('background: ' + $('#myCanvas').css('background'));
}
$('#red, #green, #blue').slider({
orientation: 'horizontal',
range: 'min',
slide: refreshSwatch,
change: refreshSwatch,
max: 255,
value: 127
});
$('#red').slider('value', 255);
$('#green').slider('value', 140);
$('#blue').slider('value', 60);
});
Problem:
The background color of #myCanvas div does not change, eventhough I call
$('#myCanvas').css('background', 'radial-gradient(#FFFFFF, ' + hex + ');');
And I have also tried calling similar code but with a colon:
$('#myCanvas').css('background: radial-gradient(#FFFFFF, ' + hex + ');');
At the same time the background color of the #swatch span changes just fine.
Simple answer: you included the ; at the end of the CSS rule. Remove it.
$('#myCanvas').css('background', 'radial-gradient(#FFFFFF, ' + hex + ')');
jQuery(document).ready(function($) {
function hexFromRGB(r, g, b) {
var hex = [
r.toString(16),
g.toString(16),
b.toString(16)
];
$.each(hex, function(nr, val) {
if (val.length === 1) {
hex[nr] = '0' + val;
}
});
return hex.join('').toUpperCase();
}
function refreshSwatch() {
var red = $('#red').slider('value'),
green = $('#green').slider('value'),
blue = $('#blue').slider('value'),
hex = '#' + hexFromRGB(red, green, blue);
$('#swatch').text(hex);
$('#swatch').css('background-color', hex);
$('#myCanvas').css('background', 'radial-gradient(#FFFFFF, ' + hex + ')');
}
$('#red, #green, #blue').slider({
orientation: 'horizontal',
range: 'min',
slide: refreshSwatch,
change: refreshSwatch,
max: 255,
value: 127
});
$('#red').slider('value', 255);
$('#green').slider('value', 140);
$('#blue').slider('value', 60);
});
#myCanvas {
background: radial-gradient(#FFFFFF, #99CC99);
width: 300px;
height: 60px;
}
#red,
#green,
#blue {
width: 300px;
margin: 15px;
}
#swatch {
padding: 10px;
margin: 5px;
color: #FFF;
}
#red .ui-slider-range {
background: #ef2929;
}
#red .ui-slider-handle {
border-color: #ef2929;
}
#green .ui-slider-range {
background: #8ae234;
}
#green .ui-slider-handle {
border-color: #8ae234;
}
#blue .ui-slider-range {
background: #729fcf;
}
#blue .ui-slider-handle {
border-color: #729fcf;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<div id="myCanvas"></div>
<p>
Select background color:
<span id="swatch"></span>
</p>
<div id="red"></div>
<div id="green"></div>
<div id="blue"></div>
Also note that you cannot have block level elements, such as div, inside inline elements, such as p.
When you click inside the input box of my to-do list and hit enter, a tiny line is added to the list. (When you enter text, the line height is regular height.) What could be causing this?
Please view my CodePen for my full code.
I'm not sure this is relevant, but here's my JavaScript:
$(function() {
$('.button').click(function() {
let toAdd = $('input[name=listItem]').val();
// Inserts li as first child of ul
$('ul').prepend('<li>' + toAdd + '</li>');
// Clears input box after clicking '+'
$('input[name=listItem]').val('');
});
// Upon hitting enter, triggers button click and prevents page from refreshing and event bubbling and capturing/trickling
$('input[name=listItem]').keypress(function(e) {
if (e.which == 13) {
$('.button').click();
e.preventDefault();
};
});
$('ul').on('click', 'li', function() {
// Upon list item click, toggleClass() adds class 'strike' for it and fadeOut() completely hides it
$(this).toggleClass('strike').fadeOut('slow');
});
});
Just check on the value you are adding:
$('.button').click(function() {
let toAdd = $('input[name=listItem]').val();
// Inserts li as first child of ul
if( toAdd == ""){
return false; // return on empty value
}
$('ul').prepend('<li>' + toAdd + '</li>');
// Clears input box after clicking '+'
$('input[name=listItem]').val('');
});
Both the below answers are right and hence upvoted but You can try and add validation to remove this situation
$(function() {
$('.button').click(function() {
let toAdd = $('input[name=listItem]').val();
if (toAdd === '') {
alert("Input should not be blank");
$('input[name=listItem]').focus();
return;
}
// Inserts li as first child of ul
$('ul').prepend('<li>' + toAdd + '</li>');
// Clears input box after clicking '+'
$('input[name=listItem]').val('');
});
// Upon hitting enter, triggers button click and prevents page from refreshing and event bubbling and capturing/trickling
$('input[name=listItem]').keypress(function(e) {
if (e.which == 13) {
$('.button').click();
e.preventDefault();
};
});
$('ul').on('click', 'li', function() {
// Upon list item click, toggleClass() adds class 'strike' for it and fadeOut() completely hides it
$(this).toggleClass('strike').fadeOut('slow');
});
});
body {
text-align: center;
background: #dfdfdf;
font-family: Helvetica;
font-size: 14px;
color: #666;
background: linear-gradient(to left, #da4453, #89216b);
}
.container {
padding: 20px;
padding-top: 5px;
width: 400px;
/* 0 is for top and bottom and auto (set to equal values for each by browser) for left-right */
margin: 0 auto;
margin-top: 40px;
background: #eee;
border-radius: 5px;
}
form {
/* Needed to display button next to input box */
display: inline-block;
}
input[type="text"] {
border: 1px solid #ccc;
height: 1.6em;
width: 29em;
color: #666;
}
/* Sets appearance of input box boundaries when user clicks inside it */
input:focus {
border-color: #da4453;
/* L to R: horizontal offset, vertical offset, blur radius. A in RGBA is alpha parameter, a number between 0.0 (fully transparent) and 1.0 (fully opaque) */
box-shadow: 0 0 8px rgba(229, 103, 23, 0.6);
outline: 0 none;
}
button.button {
margin-left: -29.8px;
/* 2px added to account for default 1px padding of input box set by user agent (browser) stylesheet */
height: -webkit-calc(1.6em + 2px);
height: calc(1.6em + 2px);
width: 25px;
color: grey;
border: none;
}
.button:hover {
cursor: pointer;
opacity: 0.8;
color: #9a9797;
}
/* Remove margins and padding from list */
ul {
margin: 0;
padding: 0;
}
/* Applies styling to any li descendants of ul (descendant combinator) */
ul li {
text-align: left;
/* Prevents default bullet points */
list-style-type: none;
margin: auto;
cursor: pointer;
position: relative;
background-color: #eee;
/* First value sets top and bottom padding; second value sets right and left */
padding: 1.5px 0;
}
/* Set all odd list items to a different color (zebra stripes) */
ul li:nth-child(odd) {
background: #f9f9f9;
}
/* Sets darker background color on hover over list items */
ul li:hover {
background-color: #ddd;
}
.strike {
text-decoration: line-through;
}
<html>
<head>
<meta charset="UTF-8">
<title>To-Do List</title>
<link rel="stylesheet" href="styles.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="designs.js"></script>
</head>
<body>
<div class="container">
<h2>To Do</h2>
<form name="listForm">
<input type="text" name="listItem" placeholder="Add new">
<button type="button" class="button">+</button>
</form>
<br><br>
<ul>
<li>Work on projects for one hour</li>
<li>Go for a walk</li>
<li>Call parents</li>
</ul>
</div>
</body>
</html>
$('.button').click(function() {
let toAdd = $('input[name=listItem]').val();
// Inserts li as first child of ul
if(toAdd == ""){
alert("Input Should no be blank");
return;
}
$('ul').prepend('<li>' + toAdd + '</li>');
// Clears input box after clicking '+'
$('input[name=listItem]').val('');
});
Try adding a check to see if there's nothing in the input box first:
$('.button').click(function() {
let toAdd = $('input[name=listItem]').val();
if (toAdd === '') return;
Using ES6 Syntax
$('.button').on('click'() => {
let toAdd = $('input[name=listItem]').val();
toAdd === '' ? return : null
I made a button in HTML that work fine on Google Chrome but does not react at all on Firefox.
My code:
function fbs_click() {
var u = location.href;
var t = document.title;
window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t) + '&s=' + encodeURIComponent(CQuote + CAuthor), 'sharer', 'toolbar=0,status=0,width=626,height=436');
}
function rSign() {
var test = Math.random();
return test > 0.5 ? 1 : -1;
}
var CQuote = "",
CAuthor = "";
function getQuote() {
$.ajax({
jsonp: "jsonp",
dataType: "jsonp",
contentType: "application/jsonp",
url: "https://api.forismatic.com/api/1.0/?",
data: {
method: "getQuote",
lang: "en",
format: "jsonp",
},
success: function(quote) {
// document.getElementById("quote").innerHTML =
CQuote = quote.quoteText;
// document.getElementById("author").innerHTML =
CAuthor = quote.quoteAuthor;
document.getElementById("author").innerHTML = CAuthor;
document.getElementById("quote").innerHTML = CQuote;
}
});
}
$(document).ready(function() {
getQuote();
})
var background = document.getElementById('backimg');
var huetarget = 0;
var huecurrent = 0;
var bright = 1;
function abyssmal() {
background.style.filter = 'hue-rotate(' + huecurrent + 'deg) ';
if (huecurrent < huetarget) {
huecurrent += Math.abs(huetarget - huecurrent) / 20
}
if (huecurrent >= huetarget) {
huecurrent -= Math.abs(huetarget - huecurrent) / 20
}
}
var interval = setInterval(abyssmal, 25);
$("#btnAnimate").on("click", function() {
huetarget += (Math.random() * 50 + 50) * rSign();
getQuote();
});
$('#tweet').on("click", function() {
window.open("https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=" + encodeURIComponent('"' + CQuote + '" -' + CAuthor), "_blank")
});
$('#facebook').on("click", function() {
fbs_click();
});
/*#myDiv{
background-color: green;
transition : background-color 2s,opacity 2s;
}
#myDiv:hover{
background-color : red;
opacity : 0.5
} */
#quotebox {
font-size: 30px;
height: auto;
}
#authorbox {
text-align: right;
}
.box {
height: auto;
margin: auto;
}
#btnAnimate {
width: 150px;
}
.share {
width: 50px;
float: right;
}
.button {
height: 50px;
padding: 0px;
vertical-align: middle;
margin-top: 40px;
color: white;
background-color: #333c5b;
border-radius: 3px;
border: none;
}
button:hover {
opacity: .8;
}
.background-tile {
background-image: url(https://image.noelshack.com/fichiers/2017/51/3/1513771628-background-1.jpg);
background-size: 1500px 900px;
height: 900px;
width: 1515px;
padding-top: 270px;
z-index: -1;
}
#backimg {
filter: hue-rotate(0deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.2/css/bootstrap.css" rel="stylesheet" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<div class="background-tile" id="backimg">
<div class="box" id="myDiv" style="padding : 50px 50px 10px 50px;width : 45%;border-radius: 5px; background-color : #476870">
<div id="quotebox">
<i class="fa fa-quote-left" style="font-size:40px;margin-left : 8px "></i>
<span id="quote"></span>
<p id=a uthorbox>-<span id="author"></span>
<p>
</div>
<button class="button quotebutton" id="btnAnimate">get quote</button>
<button class=" share button fa fa-facebook" id="facebook"></button>
<button class=" share button fa fa-twitter" id="tweet" style=" margin-right: 25px;"></button>
</div>
</div>
I doublechecked that only phrasing elements were nested inside the button.
Question: Why does the button not react on Firefox.
Some HTML methodologies are not supported via crossed-browsers.
For example, some features can work on Mozilla and Internet Explorer, but not on Chrome.
However, in this case it's demonstrating the BODY tag is overlapping your content. It may be an error with Mozilla in particular with Codepen.io, as W3schools validated that the button feature works on this browser.
You placed everything inside #backimg, which has z-index: -1, thus sending all its contents below its parent, which is <body>. This means that, even though visible, your contents sit below an invisible click-catcher (<body>).
Firefox seems to apply the z-index, although, AFAIK, the element should be position-ed (have a position value set to anything except static, which is default) for z-index to apply. Chrome doesn't apply it, because #backimg has the implicit position:static.
Closing #backimg before opening #mydiv fixes the problem and makes your HTML valid. It's not really clear how your layout is supposed to look, but here's my attempt at fixing it: https://codepen.io/anon/pen/ZvXXqP
Another problem with your pen had was that it was loading jQuery after Bootstrap's JavaScript, which requires jQuery.
I am trying to use jQuery to change some HTML text by changing a slider, I figured out how to do that, but I also need to do it only if a checkbox is on, how do I put both in, and then how do I make it only do it when the checkbox is clicked, I am doing this with arrays, because I'm trying to do it in time, not decimals. Here is the link to my current code: https://codepen.io/2cheeky4you/pen/QqGKpy
$(document).on('input change', '#range-slider', '#voiceover', function() {
//Listen to slider changes (input changes)
var v=$(this).val(); //Create a Variable (v), and store the value of the input change (Ex. Image 2 [imageURL])
var q = document.querySelector('input[id="voiceover"]');
var voiceovermain = ["<span>$0.00</span>",voiceoverslider[0]];
$('#sliderStatus').html(imageUrl[v]);
$('#sliderPrice').html( sizeRange[v] );
$('#voiceoverslider').html( sizeRange[v] );
$('#voiceoverspan').html( voiceover[q] );
$("#img").prop("src", imageUrl[v]); // Modify the Images attribute src based on the sliders value, and input the value inside the imageURL[v] to display image
});
This is one of my first times using the code thing on this website, so pardon my messed up whitespaces.
I English very well :) so I'm sorry if something doesn't make sense. Just tell me in the comments if it doesn't.
I think you wish to show two prices based on the slider position, one being optionnal depending on the checkbox.
You array idea is not the best way to do it. I think you should use the slider value as an integer and calculate your prices with it.
So the first thing is to define your two prices. Then simply do some maths.
I defined your second price as $5 per slider knotch (which is 5 seconds of video duration), for this example.
Feel free to ask questions about the code if there is anything unclear.
var sliderUnit = 5; // 5 seconds of video duration per slider notch
var basePrice = 100;
var price = 10;
var subPrice = 5;
$(document).on('input change', '#range-slider, #voiceover', function() { //Listen to slider changes (input changes)
var slider=parseInt($('#range-slider').val());
var voiceOption = $('#voiceover');
console.log(slider); // returns an integer from 0 to 34
// Time
var seconds = (slider*5)%60;
var minutes = Math.floor(slider*5/60);
if(seconds<10){seconds= "0"+seconds} // Leading zero
$('#sliderStatus').html('<span>'+minutes+":"+seconds+'</span>');
// Price for video duration
var price1 = (slider*price) +basePrice;
$('#sliderPrice').html('<span>$'+price1+'.00</span>');
// Price for voiceover
var price2 = slider*subPrice;
if( voiceOption.is(":checked") ){
$('#voiceoverspan').html('<span>$'+price2+'.00</span>');
}else{
$('#voiceoverspan').html('<span>$0.00</span>');
}
});
// ::::: Range Slider Thumb ::::: //
$("#range-slider").on("mousedown mouseup", function() { //1. When user clicks their mouse down on the Range-Slider
$(this).toggleClass("thumb-down hover-ring thumb-up hover-ring-out");
});
#slider_count {
margin:0px auto;
width:200px;
padding:20px 20px;
text-align:center;
background-color:yellow;
}
/* ::::::::::::::::::::Range Slider Styles::::::::::::::::::::::::: */
.range-slider-block {
margin:0px auto;
width:90%;
}
#range-slider {
padding:40px 0px;
width:100%;
/*outline: 1px solid green;*/
}
/* Remove Range Sliders Default Styles*/
input[type=range]{
-webkit-appearance: none;
}
/* Track */
input[type=range]::-webkit-slider-runnable-track {
height: 10px;
background: #d7d7d7;
border: none;
border-radius: 6px;
}
input[type=range]:focus {
outline: none;
}
/* Thumb */
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
border: none;
height: 30px;
width: 30px;
border-radius: 50%;
background: #46947F;
margin-top: -9px;
transition: box-shadow 0.5s;
}
input[type=range]:hover::-webkit-slider-thumb {
box-shadow: 0 0 0 10pt rgba(190,190,190,0.4);
cursor:pointer;
}
/* JS Stykes */
/* Changes Thumb color to darker green when mousedownn */
input[type=range].thumb-down::-webkit-slider-thumb {
background:#316557;
}
/* Changes Thumb color back to light green when mouseup */
input[type=range].thumb-up::-webkit-slider-thumb {
background:#46947F;
}
/* Changes Ring color Green */
input[type=range].hover-ring::-webkit-slider-thumb {
box-shadow: 0 0 0 6pt rgba(70,148,127,0.46);
cursor:pointer;
}
input[type=range].hover-ring-out::-webkit-slider-thumb {
box-shadow: 0 0 0 0pt rgba(0,0,0,0);
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="range-slider-block">
<input type="range" id="range-slider" class="thumb-up hover-ring-out" value="0.0" min="0" max="34" step="1" />
</div>
<div id="slider_count">Time = <span id="sliderStatus">0:00</span></div>
<br/>
<div id="slider_count">Subprice (Video Duration) = <span id="sliderPrice">$0.00</span></div>
<br/>
<label for="voiceover">Would you like a voiceover?</label>
<input type="checkbox" id="voiceover" name="voiceover" checked>
<div id="slider_count">Subprice (for voiceover): = <span id="voiceoverspan">$0.00</span></div>
</form>
Notice that I also improved the handler to add/remove classes on the slider...
CodePen
Hey I found the issue with your code and put a new codepen up: https://codepen.io/anon/pen/LzbBOx?editors=1111
Imediately after
function() {
you should put:
var check = $('#voiceover')[0];
if (check.checked) {
// your entire function's code here
}
I added a section to your code and modified it a little. Basically I added an if statement that checked if the check was on or not and then copied the value of the slider price into it. Of course you can do anything you want with the value but I was not sure exactly what value you wanted for the subprice. Good luck.
var sizeRange = [" <span>$100.00</span>",
" <span>$110.00</span>",
"<span>$120.00</span>",
"<span>$130.00</span>",
"<span>$140.00</span>",
"<span>$150.00</span>",
" <span>$160.00</span>",
" <span>$170.00</span>",
" <span>$180.00</span>",
" <span>$190.00</span>",
" <span>$200.00</span>",
" <span>$210.00</span>",
" <span>$220.00</span>",
" <span>$230.00</span>",
" <span>$240.00</span>",
" <span>$250.00</span>",
" <span>$260.00</span>",
" <span>$270.00</span>",
" <span>$280.00</span>",
" <span>$290.00</span>",
" <span>$300.00</span>",
" <span>$310.00</span>",
" <span>$320.00</span>",
" <span>$350.00</span>",
" <span>$380.00</span>",
" <span>$410.00</span>",
" <span>$440.00</span>",
" <span>$470.00</span>",
" <span>$500.00</span>",
" <span>$530.00</span>",
" <span>$560.00</span>",
" <span>$590.00</span>",
" <span>$620.00</span>",
" <span>$650.00</span>",
" <span>$680.00</span>"
];
var imageUrl = [" <span>:10</span>",
" <span>:15</span>",
"<span>:20</span>",
"<span>:25</span>",
"<span>:30</span>",
"<span>:35</span>",
" <span>:40</span>",
" <span>:45</span>",
" <span>:50</span>",
" <span>:55</span>",
" <span>1:00</span>",
" <span>1:05</span>",
" <span>1:10</span>",
" <span>1:15</span>",
" <span>1:20</span>",
" <span>1:25</span>",
" <span>1:30</span>",
" <span>1:35</span>",
" <span>1:40</span>",
" <span>1:45</span>",
" <span>1:50</span>",
" <span>1:55</span>",
" <span>2:00</span>",
" <span>2:15</span>",
" <span>2:30</span>",
" <span>2:45</span>",
" <span>3:00</span>",
" <span>3:15</span>",
" <span>3:30</span>",
" <span>3:45</span>",
" <span>4:00</span>",
" <span>4:15</span>",
" <span>4:30</span>",
" <span>4:45</span>",
" <span>5:00</span>",
]; //adds the times instead of regular numbers.
var voiceoverslider = [" <span>$100.00</span>",
" <span>$110.00</span>",
"<span>$120.00</span>",
"<span>$130.00</span>",
"<span>$140.00</span>",
"<span>$150.00</span>",
" <span>$160.00</span>",
" <span>$170.00</span>",
" <span>$180.00</span>",
" <span>$190.00</span>",
" <span>$200.00</span>",
" <span>$210.00</span>",
" <span>$220.00</span>",
" <span>$230.00</span>",
" <span>$240.00</span>",
" <span>$250.00</span>",
" <span>$260.00</span>",
" <span>$270.00</span>",
" <span>$280.00</span>",
" <span>$290.00</span>",
" <span>$300.00</span>",
" <span>$310.00</span>",
" <span>$320.00</span>",
" <span>$350.00</span>",
" <span>$380.00</span>",
" <span>$410.00</span>",
" <span>$440.00</span>",
" <span>$470.00</span>",
" <span>$500.00</span>",
" <span>$530.00</span>",
" <span>$560.00</span>",
" <span>$590.00</span>",
" <span>$620.00</span>",
" <span>$650.00</span>",
" <span>$680.00</span>"
];
$('#sliderPrice').html(sizeRange[0]);
$("#voiceover").on("change",function(){
});
$(document).on("change", '#range-slider', function() { //Listen to slider changes (input changes)
var v = $(this).val(); //Create a Variable (v), and store the value of the input change (Ex. Image 2 [imageURL])
var q = $("#slider_count").val();
var voiceovermain = ["<span>$0.00</span>",
voiceoverslider[0]
];
$('#sliderStatus').html(imageUrl[v]);
$('#sliderPrice').html(sizeRange[v]);
$('#voiceoverslider').html(sizeRange[v]);
//---------------------------------------------------------
if($("#voiceover").is(":checked")){
$("#voiceoverspan").html("");
$('#sliderPrice').clone().appendTo("#voiceoverspan");
} else {
$('#voiceoverspan').html("$0.00");
}
//-----------------------------------------------------------
$("#img").prop("src", imageUrl[v]); // Modify the Images attribute src based on the sliders value, and input the value inside the imageURL[v] to display image
});
// ::::: Range Slider Thumb ::::: //
$("#range-slider").on("mousedown", function() { //1. When user clicks their mouse down on the Range-Slider
$(this).removeClass().addClass("thumb-down"); //1.1 Remove default class from CSS, and add the class .thumb-down (changes background color)
$(this).addClass("hover-ring"); //1.2 Remove default class from CSS, and add the class .hover-ring (changes box-shadow to a green color)
});
$("#range-slider").on("mouseup", function() { //2. When user mouse-up on Range-Slider
$(this).addClass("thumb-up"); //2.1 Changes thumb color back to light green
$(this).addClass("hover-ring-out"); //2.2 Remove Box-Shadow
});
#slider_count {
margin: 0px auto;
width: 200px;
padding: 20px 20px;
text-align: center;
background-color: yellow;
}
/* ::::::::::::::::::::Range Slider Styles::::::::::::::::::::::::: */
.range-slider-block {
margin: 0px auto;
width: 90%;
}
#range-slider {
padding: 40px 0px;
width: 100%;
/*outline: 1px solid green;*/
}
/* Remove Range Sliders Default Styles*/
input[type=range] {
-webkit-appearance: none;
}
/* Track */
input[type=range]::-webkit-slider-runnable-track {
height: 10px;
background: #d7d7d7;
border: none;
border-radius: 6px;
}
input[type=range]:focus {
outline: none;
}
/* Thumb */
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
border: none;
height: 30px;
width: 30px;
border-radius: 50%;
background: #46947F;
margin-top: -9px;
transition: box-shadow 0.5s;
}
input[type=range]:hover::-webkit-slider-thumb {
box-shadow: 0 0 0 10pt rgba(190, 190, 190, 0.4);
cursor: pointer;
}
/* JS Stykes */
/* Changes Thumb color to darker green when mousedownn */
input[type=range].thumb-down::-webkit-slider-thumb {
background: #316557;
}
/* Changes Thumb color back to light green when mouseup */
input[type=range].thumb-up::-webkit-slider-thumb {
background: #46947F;
}
/* Changes Ring color Green */
input[type=range].hover-ring::-webkit-slider-thumb {
box-shadow: 0 0 0 6pt rgba(70, 148, 127, 0.46);
cursor: pointer;
}
input[type=range].hover-ring-out::-webkit-slider-thumb {
box-shadow: 0 0 0 0pt rgba(0, 0, 0, 0);
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="range-slider-block">
<input type="range" id="range-slider" value="0.0" min="0" max="34" step="1" />
</div>
<div id="slider_count">Time = <span id="sliderStatus">:10</span></div>
<br/>
<div id="slider_count">Subprice (Video Duration) = <span id="sliderPrice">$0.00</span></div>
<br/>
<label for="voiceover">Would you like a voiceover?</label>
<input type="checkbox" id="voiceover" name="voiceover" checked>
<div id="slider_count">Subprice (for voiceover): = <span id="voiceoverspan">$0.00</span></div>
</form>