I wanted to implement a slider control that changes the brightness of the image, much like the one shown at this link :
http://camanjs.com/examples/
I am fairly new to javascript and this is proving to be rather difficult. So right now, I am using the CamanJS library but unfortunately am not able to replicate that. I tried reverse engineering the example, but gosh the example is very complicated and not at all readable! Anyways, heres the problem with my implementation :
//this is the event handler called when the slider value changes
function brightnessControl(e, ui) {
//mainImage is the id of the canvas that holds the image
Caman("#mainImage", function() {
this.brightness(ui.value);
this.render();
});
}
the original image is overwritten with a new image with the brightness settings. So eventually, I end up with just a plain white or black image. Any help would be greatly appreciated! Thanks in advance!
You can achieve the desired effect with a canvas element, CSS3 filter and pure JavaScript:
HTML
<input id="bri" type="text" value="1"/>
<canvas id="img"></canvas>
JavaScript
window.onload = function () {
var context = document.getElementById('img').getContext('2d');
/* Loading the image at first */
var base_image = new Image();
base_image.src = 'http://images.google.com/intl/fr_ALL/images/logos/images_logo_lg.gif';
context.drawImage(base_image, 0, 0);
/* Function trigerred when we leave the input */
document.getElementById('bri').onblur = function () {
var amount = this.value;
var img = document.getElementById('img');
/* We change the brightness of the canvas itself */
img.setAttribute('style', 'filter:brightness(' + amount + '); -webkit-filter:brightness(' + amount + '); -moz-filter:brightness(' + amount + ')');
}
};
Live Demo
To read full implementation check this website How to Create an Image Brightness Control Slider
rangeInput = document.getElementById('range');
container = document.getElementsByClassName('container')[0];
rangeInput.addEventListener("mousemove",function(){
container.style.filter = "brightness(" + rangeInput.value + "%)";
});
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container{
background: url(https://codingdebugging.com/wp-content/uploads/2020/07/include-how-to-create-an-image-brightness-control-slider.jpg) no-repeat center;
min-height: 100vh;
background-size: cover;
display: flex;
align-items: center;
justify-content: center;
}
.brightness-box{
width: 400px;
height: 60px;
background: #f9f9f9;
border-radius: 8px;
padding: 0 20px;
display: flex;
align-items: center;
justify-content: space-between;
}
.brightness-box i{
margin: 0 10px;
}
#range{
width: 100%;
-webkit-appearance: none;
background: #0a85ff;
height: 3px;
outline: none;
}
#range::-webkit-slider-thumb{
-webkit-appearance: none;
width: 22px;
height: 22px;
background: #333;
border-radius: 50%;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<title>Brightness Control - Coding Debugging</title>
<!-- Font Awesome Icon -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css">
</head>
<body>
<div class="container">
<div class="brightness-box">
<i class="far fa-sun"></i>
<input type="range" id="range" min="10" max="100" value="100">
<i class="fas fa-sun"></i>
</div>
</div>
</body>
</html>
//this is the event handler called when the slider value changes
function brightnessControl(e, ui) {
//mainImage is the id of the canvas that holds the image
Caman("#mainImage", function() {
this.style.filter='brightness(ui.value)';//like this: filter: brightness(0.4)
//this.brightness(ui.value);
// this.render(); i don/t know this is useful? you judge it by yourself
});
}
the brightness is from 0 to 1.
The following will work in CSS 2.1+. Please note that I have used HTML5 input type="range" only for ease of use in this example. Javascript fallback code is also implemented in this example for browsers that do not support this (input type will default to text).
Optimally a custom slider would be implemented, but I believe this question is about brightness control and not so much about the slider.
The way this works is by overlapping the image with some element of equal proportions and with opacity depending on the slider/text input value. The background color of this element will be white for values > 50, and black for values < 50.
Link to JS Fiddle
#HTML
<div id="container">
<div id="brightness"></div>
<img src="http://placehold.it/400x400" />
</div>
Brightness (0 - 100):<br />
<input type="range" id="controls" value="50" min="0" max="100" maxlength="3">
#Javascript
window.onload = function()
{
var brightness = document.getElementById('brightness');
controls = document.getElementById('controls');
controls.onkeyup = controls.onchange = function()
{
var brightness = document.getElementById('brightness'),
val = parseInt(this.value) - 50;
if (val > 50 || val < -50)
return false;
brightness.style.backgroundColor = val > 0 ? 'white' : 'black';
brightness.style.opacity = Math.abs(val/100) * 2;
}
}
#CSS
#container{
width:400px;
height:400px;
margin-bottom:10px;
border:1px solid rgb(127, 127, 127);
}
#brightness{
width:400px;
height:400px;
background:white;
position:absolute;
opacity:0;
}
#controls{
width:400px;
height:22px;
padding:0 5px;
}
Related
I've used a code from this answer to style HTML5 input in my GRAV CMS website.
The rendered part of HTML markup:
<div class="form-data" data-grav-field="range" data-grav-disabled="" data-grav-default="40">
<div class="form-input-wrapper ">
<input name="data[space]" value="40" type="range" style="display: inline-block;vertical-align: middle;" oninput="space_output.value = space.value" min="40" max="350" step="10" class="form-input " id="space" required="required">
<output name="data[space]" id="space_output" style="display: inline-block;vertical-align: baseline;padding: 0 0.5em 5px 0.5em;"> 40 </output>
</div>
</div>
The JS code is taken from the answer above and placed in at the beginning of my custom.js file:
document.getElementById("space").oninput = function() {
var value = (this.value-this.min)/(this.max-this.min)*100
this.style.background = 'linear-gradient(to right, #eec170 0%, #eea624 ' + value + '%, #839788 ' + value + '%, #a6d86c 100%)'
};
So, this part works without any flaws.
The problem:
With JS code the behaviour of input is incorrect, once the page is loaded background color is not reflecting the ball position of the default position 40, because it's not the center.
Once the slider position is changed, the background colors are changed depending on the slider position.
That's the lesser problem, but the major problem is that the <output> field no longer displays the new values. It's has been stuck to 40.
How could it be fixed?
Try this example. I have added one more (hidden) input for calculate range and wrapped it with a form tag to get the value from the output. I also added styles and refactored the gradient calculation to javascript.
document.addEventListener('DOMContentLoaded', function() {
const slider = document.getElementById('range');
// Calculate gradient persent (0% - 100%)
const calcGradientPersent = value => (100 * value) / 360;
// Default value when load page
const initValue = slider.value;
let persent = calcGradientPersent(initValue);
// Set default inline style
slider.style.background = `linear-gradient(to right, #eec170 0%, #eea624 ${persent}%, #839788 ${persent}%, #a6d86c 100%)`;
// Input Range handler
slider.addEventListener('input', event => {
// Get value from input
const value = event.target.value;
persent = calcGradientPersent(value);
// Update inline style
slider.style.background = `linear-gradient(to right, #eec170 0%, #eea624 ${persent}%, #839788 ${persent}%, #a6d86c 100%)`;
});
});
*,
::after,
::before {
margin: 0;
padding: 0;
box-sizing: border-box;
}
input[type='range'] {
appearance: none;
border-radius: 1rem;
}
input[type='range']:focus {
outline: none;
}
input[type='range']::-webkit-slider-runnable-track {
width: 100%;
height: 0.4rem;
cursor: pointer;
border-radius: 1rem;
border: 1px solid #eea624;
}
input[type='range']::-webkit-slider-thumb {
height: 1rem;
aspect-ratio: 1;
border-radius: 50%;
border: 2px solid gray;
background: #d8d7f3;
cursor: pointer;
appearance: none;
margin-top: -0.35rem;
}
<div class="form-data" data-grav-field="range" data-grav-disabled="" data-grav-default="40">
<form oninput="result.value=parseInt(range.value)+parseInt(step.value)" class="form-input-wrapper">
<input name="range" value="40" type="range" style="display: inline-block; vertical-align: middle" min="0" max="350" step="10" class="form-input" id="range" required="required" />
<input type="number" id="step" value="0" hidden />
<output name="result" id="space_output" for="range step" style="display: inline-block; vertical-align: baseline; padding: 0 0.5em 5px 0.5em">
40
</output>
</form>
</div>
I have a progress bar that changes based on the currentCount(I'm gonna replace it with a variable containing numbers value that will automatically increase). Currently, I set it just a static number 850 just for example. I also have input to set the target amount which currently I set to 1000(Can change anytime as we like) just for example.
Currently, the progress bar will only change every time I click the .pstbtn when setting the target amount. I want the progress bar to change automatically, in real-time based on the value changes that will happen in currentCount. To reach 100%, it should be based on the target amount that I set.
Please check out the snippet below.
$(document).ready(function() {
$(".postbtn").on('click', function() {
var currentCount = 850;
var progress = (currentCount / $('#q10').val()) * 100;
progress = (currentCount / $('#q10').val()) * 100;
$("#myBar").width(progress + '%');
$("#label").text(progress + '%');
});
});
#myProgress {
position: relative;
width: 100%;
height: 30px;
background-color: #ddd;
}
#myBar {
position: absolute;
width: 0%;
height: 100%;
background-color: #4CAF50;
}
#label {
text-align: center;
line-height: 30px;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
Total likes target:<br>
<input type="text" name="Total" id="q10" value="1000"><br> <br>
<input class="postbtn" style="width: auto; font-size: 16px;" type="button" value="Set Target">
<br><br><div id="myProgress">
<div id="myBar">
<div id="label"> 0%</div>
</div>
</div>
Hope anyone could help me modify the code to achieve my aim. Thank you in advance!
Is this the sort of effect that you were trying to accomplish? Rather than a text input I changed it to a number and set the step property so that changes are immediately apparent ( dependant upon target number specified )
var currentCount = 850;
/* utility function that take the numeric input and calculates/displays the percentage */
const getpercentage=(i)=>{
/* can not go beyond 100%!!! */
var progress = Math.min( ( currentCount / i ).toFixed(2) * 100, 100 );
$("#myBar").width( progress + '%' );
$("#label").text( progress + '%' );
}
/*
when the button is clicked, open
a dialog to set a new target. Call the
helper to display re-calculated percentage
*/
$('.postbtn').on('click',e=>{
let i=prompt('Set the Target',currentCount);
if( !isNaN( i ) ){
currentCount=i;
getpercentage( $('#q10').val() );
}
})
/* call the helper when the input changes */
$('#q10').on('change',(e)=>{
getpercentage( e.target.value )
});
/* call the helper at pageload */
getpercentage( $('#q10').val() );
#myProgress {
position: relative;
width: 100%;
height: 30px;
background-color: #ddd;
}
#myBar {
position: absolute;
width: 0%;
height: 100%;
background-color: #4CAF50;
}
#label {
text-align: center;
line-height: 30px;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Total likes target:<br>
<!-- for simplicity changed this to number input -->
<input type="number" name="Total" id="q10" value="1000" step=10><br> <br>
<input class="postbtn" style="width: auto; font-size: 16px;" type="button" value="Set Target">
<br><br>
<div id="myProgress">
<div id="myBar">
<div id="label"> 0%</div>
</div>
</div>
I created this range slider, and i would like to fill the "lower" section of the slider with a green color similar to the blue in the example picture.
I've tried every technique i could find on the web. I read that Internet Explorer supports code for this sort of thing, but most modern browsers will need a hack to achieve this affect. I tried a gradient technique but it seemed a little too hacky for me. Nothing i try sticks.
Does anybody know a simple way to fill the lower fill section? There has to be a way-
https://codepen.io/stinkytofu3311/pen/GmKxoW
var sizeRange = ["11x17 - Starting Price <span>- $19.99</span>", // Store string inside of an Array
"24x36 - Starting Price <span>- $29.99</span>",
"70x90 - Starting Price <span>- $39.99</span>",
"120x50 - Starting Price <span>- $49.99</span>",
"67x18 - Starting Price <span>- $59.99</span>",
"19x30 - Starting Price <span>- $69.99</span>"]
var imageUrl = new Array(); // Store images inside of an Array
imageUrl[0] = 'http://svgshare.com/i/1Ak.svg';
imageUrl[1] = 'http://svgshare.com/i/1AQ.svg';
imageUrl[2] = 'http://svgshare.com/i/1Bb.svg';
imageUrl[3] = 'http://svgshare.com/i/1Am.svg';
imageUrl[4] = 'http://svgshare.com/i/1CG.svg';
imageUrl[5] = 'http://svgshare.com/i/1By.svg';
$('#sliderPrice').html( sizeRange[0] );
$(document).on('input 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])
$('#sliderStatus').html( $(this).val() );
$('#sliderPrice').html( sizeRange[v] );
$("#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 Removes Box-Shadow
});
#import url('https://fonts.googleapis.com/css?family=Roboto');
.product-range-wrapper {
displat: -webkit-flex;
displat:flex;
-webkit-flex-direction: column;
flex-direction:column;
max-width:600px;
margin:0px auto;
/*outline: 1px solid purple;*/
}
.product-range-block {
display: -webkit-flex;
display:flex;
-webkit-flex-direction: row;
flex-direction: row;
width:100%;
height:100%;
/*outline: 1px solid red;*/
}
.ref-height-block {
flex-grow:3;
/*background-color:red;*/
}
.size-chart-block {
flex-grow:9;
/*background-color:green;*/
}
.product-range-block img {
width:90%;
/*outline: 1px solid blue;*/
}
#img {
width: 100% !important;
}
/* ::::::::::::::::::::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 Styles */
/* 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;
}
/* Input Value Styles */
#slider_count {
margin:0px auto;
width:100%;
padding:0px 20px;
text-align:center;
}
#sliderPrice {
font-family: 'Roboto', sans-serif;
font-size:22px;
font-weight:600;
}
#sliderPrice span {
font-weight:600;
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<div class="product-range-wrapper">
<div class="product-range-block">
<div class="ref-height-block">
<img src="http://svgshare.com/i/1Ba.svg" alt="Product Height Refrence" height="" width="">
</div>
<div class="size-chart-block">
<img src="http://svgshare.com/i/1Ak.svg" style='' id='img'/>
</div>
</div>
<div id="slider_count"><span id="sliderPrice">0</span></div>
<div class="range-slider-block">
<input type="range" id="range-slider" value="0.0" min="0" max="5" step="1" />
</div>
</div>
<div id="slider_count">Slider Value = <span id="sliderStatus">0</span></div>
<br/>
I managed to get a working version here: http://codepen.io/anon/pen/LyxYVY
var sheet = document.createElement('style'),
$rangeInput = $('.range'),
prefs = ['webkit-slider-runnable-track', 'moz-range-track', 'ms-track'];
document.body.appendChild(sheet);
var getTrackStyle = function (el) {
var curVal = el.value,
style = '';
for (var i = 0; i < prefs.length; i++) {
style += '.range::-' + prefs[i] + '{background: linear-gradient(to right, #34495e 0%, #34495e ' + curVal*20 + '%, #fff ' + curVal + '%, #fff 100%)}';
}
return style;
}
$rangeInput.on('input', function () {
sheet.textContent = getTrackStyle(this);
});
You can use the webkit, firefox and ms track options. However they will only work on compatible browsers.
I'm pretty new with Javascript and jQuery, and can't seem to indentify the reason why my code acts like it does.
I have created two seemingly identical functions to change the background color of an input field.
Their goal is to turn the background color of the given input field to the color #00FF7F if anything is typed in the field. And if not, the field should be transparent.
Code JS:
$(document).ready(function () {
var $input1 = $("#logindata1");
var $input2 = $("#logindata2");
function onChangeInput1() {
$input1.css("background-color", "#00FF7F");
var value = $.trim($(".form-control").val());
if (value.length === 0) {
$input1.css("background-color", "transparent");
}
}
function onChangeInput2() {
$input2.css("background-color", "#00FF7F");
var value = $.trim($(".form-control").val());
if (value.length === 0) {
$input2.css("#background-color", "transparent");
}
}
$input1.on("keyup", onChangeInput1);
$input2.on("keyup", onChangeInput2);
});
css:
#loginbox {
width: 400px;
height: 200px;
margin-left: auto;
margin-right: auto;
margin-top: 25%;
}
.logindata {
margin-left: auto;
margin-right: auto;
margin-top: 20px;
height: 60px;
width: 290px;
transition: 0.25s ease;
}
.form-control {
margin-left: auto;
margin-right: auto;
height: 55px;
width: 288px;
border-style: none;
background-color: transparent;
text-align: center;
border: solid 2px #00FF7F;
transition: 0.25s ease;
font-size: 25px;
font-family: "Trebuchet MS";
}
.form-control:hover {
box-shadow: 0px 0px 30px #2E8B57;
}
::-webkit-input-placeholder {
color: #00FF7F;
}
Simple HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test</title>
<!-- Stylesheet link -->
<link rel="stylesheet" type="text/css" href="assets/style.css">
<!-- jQuery link -->
<script type="text/javascript" src="assets/vendor/jquery-3.1.0.min.js"></script>
</head>
<body>
<div id="loginbox">
<div class="logindata" id="logindata1">
<input type="text" class="form-control" placeholder="Username">
</div>
<div class="logindata" id="logindata2">
<input type="password" class="form-control" placeholder="Password">
</div>
</div>
<!-- Javascript link-->
<script type="text/javascript" src="assets/js/javascript.js"></script>
</body>
On the jsbin above, try typing in both the Username and Password field to see how they react differently.
Images of what happens. Didn't want to include all images here:
http://imgur.com/a/qgubP
I realize there probably is a way to compromise my js/jquery into 1 function that each input field calls instead of have a function for each.
If both of these fields are required, here's a much simpler solution using CSS only.
Add the attribute required to your <input> tags and then use the pseudo-class :valid.
.form-control:valid {
background-color: #00FF7F;
}
Code snippet:
#loginbox {
width: 400px;
height: 200px;
margin-left: auto;
margin-right: auto;
margin-top: 25%;
}
.logindata {
margin-left: auto;
margin-right: auto;
margin-top: 20px;
height: 60px;
width: 290px;
transition: 0.25s ease;
}
.form-control {
margin-left: auto;
margin-right: auto;
height: 55px;
width: 288px;
border-style: none;
background-color: transparent;
text-align: center;
border: solid 2px #00FF7F;
transition: 0.25s ease;
font-size: 25px;
font-family: "Trebuchet MS";
}
.form-control:hover {
box-shadow: 0px 0px 30px #2E8B57;
}
::-webkit-input-placeholder {
color: #00FF7F;
}
.form-control:valid {
background-color: #00FF7F;
}
<div id="loginbox">
<div class="logindata" id="logindata1">
<input type="text" class="form-control" placeholder="Username" required>
</div>
<div class="logindata" id="logindata2">
<input type="password" class="form-control" placeholder="Password" required>
</div>
</div>
jsFiddle : https://jsfiddle.net/7vzjz2u5/3/
jQuery
$(document).ready(function() {
$('.change-background').on('change', function() {
var $this = $(this);
var value = $.trim($this.val());
// toggleClass can be provided a bool value,
// If we provide true we add class, if false we remove class
$this.toggleClass('filled-background', value.length !== 0);
}).change();
// We also want to call a 'change' event on
// all inputs with the change-background class just incase the page has
// pre-filled in values
});
Instead of listening for the keyup event and then running a function, just create a listener on the change event, also if we just apply one class to all inputs we want the background colour to change on, we can just create one listener which will do it for any input with the class change-background.
Html
<div id="loginbox">
<div class="logindata" id="logindata1">
<input type="text" class="change-background form-control" placeholder="Username">
</div>
<div class="logindata" id="logindata2">
<input type="password" class="change-background form-control" placeholder="Password">
</div>
</div>
Css (the extra class for background color)
.filled-background {
background-color: #00FF7F;
}
Also side note
listening for keyup is back, someone may want to copy and paste their username and password and if they do this it won't trigger an keyup event if they use right click and paste.
Your code clears the background color when the length is 0. The way it checks the length is with this snippet of code:
var value = $.trim($(".form-control").val());
The selector $(".form-control") will select all elements with the CSS class of .form-control. This is a problem because there is more than one of them; in this case, it will always return the value from the first element found.
You should change the code to check for the specific control by searching by ID, like so:
var value = $.trim($("#logindata1 input").val()); //get user ID
var value = $.trim($("#logindata2 input").val()); //get password
You have some minor mistakes, but no worry. We can fix it.
First Problem
Other answers are pointing something important: you are trying to get the value selecting all elements with form-control class.
var value = $.trim($(".form-control").val());
You can do it, replacing your selector by your already declared variables $input1 and $input2. This way:
var value = $.trim($input1.val());
var value = $.trim($input2.val());
Second
Ok. First problem solved. The second problem is in your second function. You trying to set an invalid css: $input2.css("#background-color", "transparent");
When should be: $input2.css("background-color", "transparent"); (without #).
Next One
Nice. Next one. The id's you are setting logindata1 and logindata2 are on your divs. So, you are wrongly trying to get the value of the div instead the value of the input. you can fix your selector by appending input, this way:
var $input1 = $("#logindata1 input");
var $input2 = $("#logindata2 input");
Finally
So, finally, it should work:
$(document).ready(function () {
var $input1 = $("#logindata1 input");
var $input2 = $("#logindata2 input");
function onChangeInput1() {
$input1.css("background-color", "#00007F");
var value = $.trim($input1.val());
if (value.length === 0) {
$input1.css("background-color", "transparent");
}
}
function onChangeInput2() {
$input2.css("background-color", "#00007F");
var value = $.trim($input2.val());
if (value.length === 0) {
$input2.css("background-color", "transparent");
}
}
$input1.on("keyup", onChangeInput1);
$input2.on("keyup", onChangeInput2);
});
Your value check is not right. With your jQuery, you are checking the value of both inputs every time.
Try checking the single inputs that you are interested in instead.
$(document).ready(function () {
var $input1 = $("#logindata1");
var $input2 = $("#logindata2");
function onChangeInput1() {
$input1.css("background-color", "#00FF7F");
var value = $.trim($input1.val());
if (value.length === 0) {
$input1.css("background-color", "transparent");
}
}
function onChangeInput2() {
$input2.css("background-color", "#00FF7F");
var value = $.trim($input2.val());
if (value.length === 0) {
$input2.css("#background-color", "transparent");
}
}
$input1.on("keyup", onChangeInput1);
$input2.on("keyup", onChangeInput2);
});
Here is my JsFiddle
I want to apply background-color change property to circle when the window slides. Like in the beginning only first circle will have background-color. and when the images slides to second screen the second circle will have only color.
Can anybody guide me how to achieve that.
JQuery:
$(document).ready(function () {
setInterval(function () {
var A = $('.gallery').scrollLeft();
if (A < 993) {
$('.gallery').animate({
scrollLeft: '+=331px'
}, 300);
}
if (A >= 993) {
$('.gallery').delay(400).animate({
scrollLeft: 0
}, 300);
}
}, 3000);
});
Here's a simple solution of your problem: http://jsfiddle.net/pjvCw/44/ but....
The way you're doing galleries is quite wrong.
You have a really sensitive CSS full of margin bugs (see in CSS code),
you calculate all by hand, which will just complicate your life one day if you'll get to add images, change widths etc...
Your buttons are positioned really wrongly, and again you don't even need to manually add them in your HTML. Let jQuery do all the job for you:
Calculate margins, widths,
Get the number of slides
generate buttons,
Make your buttons clickable
Pause gallery on mouseenter (loop again on mouseleave)
LIVE DEMO
This is the way you should go with your slider:
HTML:
<div class="galleryContainer"> <!-- Note this main 'wrapper' -->
<div class="gallery">
<div class="row">
<!-- ..your images.. -->
</div>
<div class="row">
<!-- ..your images.. -->
</div>
</div>
<div class="content-nav-control"></div> <!-- Let jQ create the buttons -->
</div>
Note the general gallery wrapper, it allows you with this CSS to make your buttons parent not move with the gallery.
CSS:
In your code, using display:inline-block; adds 4px margin to your elements, ruining your math. So you just need to apply font-size:0; to remove that inconvenience.
As soon I did that the math was working and the right width was than 340px, having 5px border for your images and 20px margin.
.galleryContainer{
/* you need that one
// to prevent the navigation move */
position:relative; /* cause .content-nav-control is absolute */
background-color: #abcdef;
width:340px; /* (instead of 350) now the math will work */
height: 265px;
}
.gallery{
position:relative;
overflow: hidden; /* "overflow" is enough */
width:340px; /* (instead of 350) now the math will work */
height: 265px;
}
.gallery .row {
white-space: nowrap;
font-size:0; /* prevent inline-block 4px margin issue */
}
.gallery img {
display: inline-block;
margin-left: 20px;
margin-top: 20px;
}
.normalimage {
height: 80px;
width: 50px;
border: 5px solid black;
}
.wideimage {
height: 80px;
width: 130px;
border: 5px solid black;
}
img:last-of-type {
margin-right:20px;
}
.content-nav-control {
position: absolute;
width:100%; /* cause it's absolute */
bottom:10px;
text-align:center; /* cause of inline-block buttons inside*/
font-size:0; /* same trick as above */
}
.content-nav-control > span {
cursor:pointer;
width: 20px;
height: 20px;
display: inline-block;
border-radius: 50%;
border:1px solid #000;
box-shadow: inset 0 0 6px 2px rgba(0,0,0,.75);
margin: 0 2px; /* BOTH MARGINS LEFT AND RIGHT */
}
.content-nav-control > span.active{
background:blue;
}
And finally:
$(function () { // DOM ready shorty
var $gal = $('.gallery'),
$nav = $('.content-nav-control'),
galSW = $gal[0].scrollWidth, // scrollable width
imgM = parseInt($gal.find('img').css('marginLeft'), 10), // 20px
galW = $gal.width() - imgM, // - one Margin
n = Math.round(galSW/galW), // n of slides
c = 0, // counter
galIntv; // the interval
for(var i=0; i<n; i++){
$nav.append('<span />'); // Create circles
}
var $btn = $nav.find('span');
$btn.eq(c).addClass('active');
function anim(){
$btn.removeClass('active').eq(c).addClass('active');
$gal.stop().animate({scrollLeft: galW*c }, 400);
}
function loop(){
galIntv = setInterval(function(){
c = ++c%n;
anim();
}, 3000);
}
loop(); // first start kick
// MAKE BUTTONS CLICKABLE
$nav.on('click', 'span', function(){
c = $(this).index();
anim();
});
// PAUSE ON GALLERY MOUSEENTER
$gal.parent('.galleryContainer').hover(function( e ){
return e.type=='mouseenter' ? clearInterval(galIntv) : loop() ;
});
});
"- With this solution, What can I do now and in the future? -"
Nothing! just freely add images into your HTML and play, and never again have to take a look at your backyard :)
Try this: http://jsfiddle.net/yerdW/1/
I added a line that gets the scrollLeft and divides it by your width (331px) to get the position and use that to select the 'active' circle:
$(".circle").removeClass("coloured");
position = Math.ceil($(".gallery").scrollLeft()/331 + 2);
if(position > $(".circle").length){
position = 1; // yes...
}
$(".content-nav-control div:nth-child("+position+")").addClass("coloured");
Red background for active circle:
.coloured {
background : red;
}
Note that you should initialise with the first circle already having the .coloured class applied.
Here you go: http://jsfiddle.net/pjvCw/41/
i added new class
.selected
{
background-color: red;
}
and modified some js code
Here is your jsfiddle edited http://jsfiddle.net/pjvCw/45/
var scrolled = 0;
var circles = $(".circle");
var colorCircle = function(index) {
for(var i=0; i<circles.length; i++) {
if(i == index) {
circles.eq(i).css("background-color", "rgba(255, 0, 0, 1)");
} else {
circles.eq(i).css("background-color", "rgba(255, 0, 0, 0)");
}
}
}
$(document).ready(function () {
setInterval(function () {
var A = $('.gallery').scrollLeft();
if (A < 993) {
$('.gallery').animate({
scrollLeft: '+=331px'
}, 300);
colorCircle(++scrolled);
}
if (A >= 993) {
$('.gallery').delay(400).animate({
scrollLeft: 0
}, 300);
colorCircle(scrolled = 0);
}
}, 3000);
colorCircle(0);
});
I added a transition to the .circle class, so it looks a little bit better:
.circle {
width: 20px;
height: 20px;
display: inline-block;
border-radius: 50%;
border:1px solid #000;
box-shadow: inset 0 0 6px 2px rgba(0,0,0,.75);
margin-right: 5px;
transition: background-color 700ms;
-webkit-transition: background-color 700ms;
}