$("#sel1").click(function () {
$("#itemed1").attr("src", "../img/tab_img_01_on.png");
$("#itemed2").attr("src", "../img/tab_img_02.png");
$("#itemed3").attr("src", "../img/tab_img_03.png");
$("#itemed4").attr("src", "../img/tab_img_04.png");
$(this).find("span").addClass("add");
$("#sel2").find("span").removeClass("add");
$("#sel3").find("span").removeClass("add");
$("#sel4").find("span").removeClass("add");
});
$("#sel2").click(function () {
$("#itemed2").attr("src", "../img/tab_img_02_on.png");
$("#itemed1").attr("src", "../img/tab_img_01.png");
$("#itemed3").attr("src", "../img/tab_img_03.png");
$("#itemed4").attr("src", "../img/tab_img_04.png");
$(this).find("span").addClass("add");
$("#sel1").find("span").removeClass("add");
$("#sel3").find("span").removeClass("add");
$("#sel4").find("span").removeClass("add");
});
$("#sel3").click(function () {
$("#itemed3").attr("src", "../img/tab_img_03_on.png");
$("#itemed1").attr("src", "../img/tab_img_01.png");
$("#itemed2").attr("src", "../img/tab_img_02.png");
$("#itemed4").attr("src", "../img/tab_img_04.png");
$(this).find("span").addClass("add");
$("#sel1").find("span").removeClass("add");
$("#sel2").find("span").removeClass("add");
$("#sel4").find("span").removeClass("add");
});
$("#sel4").click(function () {
$("#itemed4").attr("src", "../img/tab_img_04_on.png");
$("#itemed1").attr("src", "../img/tab_img_01.png");
$("#itemed2").attr("src", "../img/tab_img_02.png");
$("#itemed3").attr("src", "../img/tab_img_03.png");
$(this).find("span").addClass("add");
$("#sel1").find("span").removeClass("add");
$("#sel2").find("span").removeClass("add");
$("#sel3").find("span").removeClass("add");
});
Hello This JQuery code is a source that changes the image when you click on the element.
It works fine, but I have a lot of iterations,
so I want to reduce my code. What should I use?
You could use a simple combination of selectors.
See sample here or in CodePen:
$(".selector").click(function () {
let index = $(this).data('index');
$(".selector").find("span").removeClass("add");
$(this).find("span").addClass("add");
$(".imgs").each( function(){
$(this).attr("src", `../img/tab_img_0${$(this).data('index')}.png`);
});
$(`.imgs[data-index="${index}"]`).attr("src", `../img/tab_img_0${index}_on.png`);
});
.add {
font-size: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="selector" data-index="1">Sel 1 <span>sample</span></button>
<button class="selector" data-index="2">Sel 2 <span>sample</span></button>
<button class="selector" data-index="3">Sel 3 <span>sample</span></button>
<button class="selector" data-index="4">Sel 4 <span>sample</span></button>
<img data-index="1" class="imgs" />
<img data-index="2" class="imgs" />
<img data-index="3" class="imgs" />
<img data-index="4" class="imgs" />
Obviously, if you are using n index > 10 you should use the padStart function.
Expendable version of same code.
function pad(v) {
return (v.length === 2 ? v : '0' + v);
}
$('[id^=sel]').click(function() {
var total = 4;
var idNumber = $(this).attr('id').match(/\d+/);
for ( i = 1; i <= total; i++ ) {
$('#itemed' + i).attr('src', '../img/tab_img_' + pad(i) + '.png');
$('#sel' + i).find('span').removeClass('add');
}
$('#itemed' + idNumber).attr('src', '../img/tab_img_' + pad(idNumber) + '_on.png');
$(this).find('span').addClass('add');
});
But I think #SnakeDrak approach is correct
This will work up to selects with the number 9. It will need a little more work to make it work with numbers grater then 9
$("[id^=sel]").click(function () { // match every element where the id starts with "sel"
var idNumber = $(this).attr('id').match(/\d+/); // get the number of given id
// reset all src paths from all given elements
$("#itemed1, #itemed2, #itemed3, #itemed4").attr("src", "../img/tab_img_01.png");
// use the idNumber to concatenate the selector and set the src
$("#itemed" + idNumber).attr("src", "../img/tab_img_0"+idNumber+"_on.png");
// remove the add class to all given elements
$("#sel1, #sel2, #sel3, #sel4").find("span").removeClass("add");
// add the "add" class to $(this) element
$(this).find("span").addClass("add");
});
Please refer below code.
$("[id^=sel]").on('click', function() {
var selectionID = ["sel1", "sel2", "sel3", "sel4"];
var itemID = ["itemed1", "itemed2", "itemed3", "itemed4"];
var selectedButton = $(this).attr("value");
$(this).find("span").addClass("add");
var indexID = selectionID.indexOf(selectedButton) + 1;
$("#itemed" + indexID).attr("src", "../img/tab_img_0" + indexID + "_on.png");
selectionID = selectionID.filter(e => e !== selectedButton);
itemID = itemID.filter(e => e !== itemID[indexID - 1]);
for (var i = 0; i < selectionID.length; i++) {
$("#" + selectionID[i]).find("span").removeClass("add");
$("#" + itemID[i]).attr("src", "../img/tab_img_0" + itemID[i].charAt(itemID[i].length - 1) + ".png");
}
});
.add {
background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button value="sel1" id="sel1"><span>sel1</span></button><br/>
<button value="sel2" id="sel2"><span>sel2</span></button><br/>
<button value="sel3" id="sel3"><span>sel3</span></button><br/>
<button value="sel4" id="sel4"><span>sel4</span></button><br/>
<img src="" id="itemed1">
<img src="" id="itemed2">
<img src="" id="itemed3">
<img src="" id="itemed4">
Related
I'm trying to write a function that when a user clicks "plus" or "minus" an input box is updated with an integer only I need to add the commas on each click manually.
If you click minus, it works at first but hitting it again renders it NaN. If I console.log this value it strips all characters after the first comma, this may not make much sense but take a look at the fiddle for a better example...
JS
function addCommas(intNum) {
return (intNum + '').replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}
$('#plus').on('click', function() {
var value = $("#propertyValueSliderValue").val();
$("#propertyValueSliderValue").val(addCommas(value));
});
$('#minus').on('click', function() {
var curVal = $("#propertyValueSliderValue").val();
var val = 500;
var newVal = curVal - val;
//newVal = newVal.replace(/,/g, "");
alert( newVal );
$("#propertyValueSliderValue").val(addCommas(newVal));
});
https://jsfiddle.net/5qhof0fq/1/
instead of var curVal = $("#propertyValueSliderValue").val(); in minus function,
remove the commas and then parse it.
var curVal = $("#propertyValueSliderValue").val();
curVal = parseInt(curVal.replace(/,/g, ""))
The issue is because the , is meaning that the value from the input cannot be coerced to an integer. You need to replace the commas before performing any mathematical operations: .replace(/,/g, '')
function addCommas(intNum) {
return (intNum + '').replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}
$('#plus').on('click', function() {
var value = $("#propertyValueSliderValue").val().replace(/,/g, '');
$("#propertyValueSliderValue").val(addCommas(value));
});
$('#minus').on('click', function() {
var curVal = $("#propertyValueSliderValue").val().replace(/,/g, '');
var val = 500;
var newVal = curVal - val;
$("#propertyValueSliderValue").val(addCommas(newVal));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-slider property-value">
<div class="slider-wrap">
<div id='minus'>-</div>
<div id='plus'>+</div>
</div>
<div class="slider-value money">
<input class="s-value number" type="tel" id="propertyValueSliderValue" value="120000" />
</div>
</div>
Alternatively, you can use a data attribute to hold the value to use in the calculation while keeping the UI-friendly value separate. You can also use another data attribute to hold the increment to be added/removed from the value so that you can DRY up the click event handlers:
function addCommas(intNum) {
return (intNum + '').replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}
var $propertySliderValue = $("#propertyValueSliderValue");
$('.inc').on('click', function() {
var value = $propertySliderValue.data('value') + $(this).data('inc');
$propertySliderValue.val(addCommas(value)).data('value', value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-slider property-value">
<div class="slider-wrap">
<div id='minus' class="inc" data-inc="-500">-</div>
<div id='plus' class="inc" data-inc="500">+</div>
</div>
<div class="slider-value money">
<input class="s-value number" type="tel" id="propertyValueSliderValue" data-value="120000" value="120,000" />
</div>
</div>
It happens because when you get the value out the #propertyValueSliderValue it is a String:
change your code to this:
$('#minus').on('click', function() {
var curVal = $("#propertyValueSliderValue").val();
var parseVal = parseInt(curVal);
var val = 500;
var newVal = parseVal - val;
//newVal = newVal.replace(/,/g, "");
alert( newVal );
$("#propertyValueSliderValue").val(addCommas(newVal));
});
It's because you read the value out of the input every time, and technically a number with the comma isn't a number in javascript.
What you can do is make a variable to keep track of the real number and only output the comma version to the user.
var value = parseInt($("#propertyValueSliderValue").val());
var interval = 500;
function addCommas(intNum) {
return (intNum + '').replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}
$('#plus').on('click', function() {
value += interval;
var commaNotatedVal = addCommas(value);
$("#propertyValueSliderValue").val(commaNotatedVal);
});
$('#minus').on('click', function() {
value -= interval;
var commaNotatedVal = addCommas(value);
$("#propertyValueSliderValue").val(commaNotatedVal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-slider property-value">
<div class="slider-wrap">
<div id='minus'>-</div>
<div id='plus'>+</div>
</div>
<div class="slider-value money">
<input class="s-value number" type="tel" id="propertyValueSliderValue" value="120000" />
</div>
</div>
My goal is to randomly change an image by clicking on a button. I have found a snippet that does that but I wanted to train my skills and work my way through it, this is what I got so far:
When I click the button, with the variable on line 11, nothing happens, but when I put the URL instead of the variable (copied from the console from line 22), it goes to the according picture. I don't get it...
When my "imageCount" is full, I get an error
var imageCount = [];
var image = ["img/01.jpg", "img/02.jpg", "img/03.jpeg", "img/04.jpeg"];
function changeImage() {
var rand = Math.floor(Math.random() * image.length);
var imageNumber = "\"url('" + image[rand] + "')\""
if (imageCount.indexOf(rand) === -1) {
imageCount.push(rand);
document.getElementById("imageWrapper").style.backgroundImage = imageNumber;
} else if (imageCount.length === image.length) {
imageCount = 0;
} else {
changeImage();
}
console.log(imageNumber);
console.log(imageCount.indexOf(rand));
console.log(image[rand]);
console.log(imageCount);
}
<link href="./style/main.css" rel="stylesheet">
<div class="wrapper">
<div class="buttonWrapper">
<button class="button" onclick="changeImage()">Next Pic</button>
</div>
<div id="imageWrapper">
<!--<img src="./img/02.jpg" alt="" id="random">-->
</div>
</div>
Two things stop your demo code from working:
#imageWrapper has no height, so the image is not displayed (probably only because your page's CSS is missing)
You reset the imageCount variable to 0 instead of []
var imageCount = [];
var image = ["//baconmockup.com/300/199/", "//baconmockup.com/300/200/", "//baconmockup.com/300/201/", "//baconmockup.com/300/202/"];
function changeImage() {
var rand = Math.floor(Math.random() * image.length);
var imageNumber = "url('" + image[rand] + "')"
if (imageCount.indexOf(rand) === -1) {
imageCount.push(rand);
document.getElementById("imageWrapper").style.backgroundImage = imageNumber;
}
else if (imageCount.length === image.length) {
imageCount = [];
}
else {
changeImage();
}
console.log(imageNumber);
console.log(imageCount.indexOf(rand));
console.log(image[rand]);
console.log(imageCount);
}
#imageWrapper {
height: 200px;
outline: solid black 1px;
}
<div class="wrapper">
<div class="buttonWrapper">
<button class="button" onclick="changeImage()">Next Pic</button>
</div>
<div id="imageWrapper">
<!--<img src="./img/02.jpg" alt="" id="random">-->
</div>
</div>
I am trying to show dynamically created li's one by one. Here is my code. Any idea why something like this would not work?
$('form').submit(function(e) {
e.preventDefault();
var userInput = $('#inputNumber').val();
console.log(outputResult);
var modifiedResult = outputResult.map(function(item) {
return '<li class="ball">' + item + '</li>'
});
$('.output').html(modifiedResult.join(""));
$('.ball').each(function(i, e) {
$(this).delay(i * 400).fadeIn();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="output"></ul>
When you do $('.output').html(modifiedResult.join("")); the lis are already visible (display property is block by default).
It would suffice to add style="display:none" in the html strings you create with #map() function - see a demo below:
var userInput = $('#inputNumber').val();
var outputResult = [1,2,3,4,5];
var modifiedResult = outputResult.map(function(item) {
return '<li style="display:none" class="ball">' + item + '</li>'
});
$('.output').html(modifiedResult.join(""));
$('.ball').each(function(i, e) {
$(this).delay(i * 400).fadeIn();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="output"></ul>
If you want to fadeIn after created user display:none initially.
$('#submit').click(function(e) {
e.preventDefault();
var userInput = 5;
var outputResult = [1, 2, 3, 4, 5];
console.log(outputResult);
var modifiedResult = outputResult.map(function(item) {
return '<li style="display:none" class="ball">' + item + '</li>'
});
$('.output').html(modifiedResult.join(""));
$('.ball').each(function(i, e) {
debugger;
$(this).delay(i * 400).fadeIn();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul class="output"></ul>
<input id="submit" type="button" value="submit" />
I have a span tag and a button tag
<span class="myspan">1</span>
<button id="add">Add +1</button>
var arr=["myspan1","myspan2","myspan3","myspan4"}
I want to append more span tag with new class from this array with increment value by clicking button.
Like this output:
<span class="myspan1">1</span>
<span class="myspan2">2</span>
<span class="myspan3">3</span>
<span class="myspan4">4</span>
i try `
this JsFiddle
But i can not add class name to new append tag from array.
Another useful link for appending tag with new class from array
http://jsbin.com/nojipowo/2/edit?html,css,js,output
...
But i can not bring my desire output at any case...enter code here
value increaseesenter code here this snippet
<script> var i = 0; function buttonClick() {i++; document.getElementById('inc').value = i; } </script> <button onclick="buttonClick();">Click Me</button> <input type="text" id="inc" value="0"></input>
another attempt...anyone can help.. to get desire output
var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];
var elements = document.getElementsByClassName("myspan");var len = backgrounds.length;
$("#add").click( function() {
(i < elements.length){
$(".new-field").append('<span class="myspan">1</span><script');
var value = parseInt($(".myspan").text(), 10) + 1;
elements[i].className += ' ' + backgrounds[i%len];
i++;
$(".background").text(i);
}
});
*/
<span class="myspan">1</span>
<button id="add">Add +1</button>
<div class="new-field">
</div>
<script> var i = 0; function buttonClick() {i++; document.getElementById('inc').value = i; } </script> <button onclick="buttonClick();">Click Me</button> <input type="text" id="inc" value="0"></input>
Try this check the span length via parseInt($(".myspan").length) .And use with Array#forEach for iterate the array instead of increment i.parseInt used convert ths string to number
var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];
var len = backgrounds.length;
$("#add").click( function() {
var len = parseInt($(".myspan").length)
backgrounds.forEach(function(a){
$(".new-field").append('<span class="'+a+'">'+(len++)+'</span>');
})
console.log($(".new-field").html())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="myspan">1</span>
<button id="add">Add +1</button>
<div class="new-field">
</div>
Check the fiddle. Hope this helps!
HTML :
<div id="mainContainer">
<span class="myspan">1</span>
</div>
<button id="add">Add +1</button>
JS :
var arr = ["myspan1", "myspan2", "myspan3", "myspan4"];
$("#add").on("click", function() {
var spans = $("span");
var classList = [];
$.each(spans, function() {
var elemCls = $(this).attr('class').length > 1 ? $(this).attr('class').split(' ') : $(this).attr('class');
if (elemCls) {
$.each(elemCls, function() {
classList.push(this.toString());
});
}
});
$.each(arr, function(i, e) {
if ($.inArray(e, classList) == -1) {
$("#mainContainer").append("<span class='" + e + "'>" + parseInt(spans.length + 1) + "</span>");
return false;
}
});
});
I have an image slider that shows all the images I have in my view in MVC5 however when I reach the last one I dont know how to make it jump back to the first one and continue from there.
The Html for the thing looks like this:
<div class="container2">
<div class="slider_wrapper">
<ul id="image_slider">
<li> <img src="#Model.ImagePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"],"../../")" width=50 height=50 /> </li>
#foreach (var item in Model.ImageGallarys)
{
<li> <img src="#item.ImagePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"],"../../")" width=50 height=50 /></li>
}
</ul>
<span class="nvgt" id="prev"></span>
<span class="nvgt" id="next"></span>
</div>
</div>
And the javascript looks like this:
function startFunction() {
$(window).load(function () {
var src = $("#image_slider").find('li:first-child img').attr('src');
$("#image_slider li:first-child ").addClass("start");
var src1 = src.replace("../..", " ");
var src2 = src1.replace('\\', "/");
$(".container2").css("background-image", 'url("' + src2 + '")');
//fadeInandOut();
});
}
function nextImageFunction() {
$("#next").click(function () {
$("li.start").next("li").addClass("start");
$("li.start").prev("li").removeClass();
var srcNext = $("li.start img").attr('src');
var srcNext1 = srcNext.replace("../..", " ");
var srcNext2 = srcNext1.replace('\\', "/");
$(".container2").css("background-image", 'url("' + srcNext2 + '")');
if($("li.start").is(":last-child"))
{
//I want the solution for this one!
}
});
}
function previousImageFunction() {
$("#prev").click(function () {
$("li.start").prev("li").addClass("start");
$("li.start").next("li").removeClass();
var srcNext = $("li.start img").attr('src');
var srcNext1 = srcNext.replace("../..", " ");
var srcNext2 = srcNext1.replace('\\', "/");
$(".container2").css("background-image", 'url("' + srcNext2 + '")');
});
if ($("li.start").is(":first-child")) {
//And also for this one!
}
}
Help me Obiwan Kenobi your my only hope!
Just do it :)
<div class="container2">
<div class="slider_wrapper">
<ul id="image_slider">
<li> <img src="#Model.ImagePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"],"../../")" width=50 height=50 /> </li>
#foreach (var item in Model.ImageGallarys) {
<li> <img src="#item.ImagePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"],"../../")" width=50 height=50 /></li>
}
</ul>
<span class="nvgt" id="prev"></span>
<span class="nvgt" id="next"></span>
</div>
</div>
And in our JS (with a little refoctoring) we will have:
// we need this support principle don't repeat yourself (DRY)
function avoidSrcSymbols(src){
return src.replace("../..", " ").src1.replace('\\', "/");
}
// This function need to improve set image via class in future//
function changeImage($src, imageSrc){
$src.css("background-image", 'url("' + imageSrc + '")');
}
function startFunction() {
$(window).load(function () {
var $firstLi = $("#image_slider").find('li:first-child');
$firstLi.addClass("start");
var src = $firstLi.find('img').attr('src');
src = avoidSrcSymbols(src);
changeImage($(".container2"), src);
//fadeInandOut();
});
}
function nextLi($currentLi){
if ($currentLi.is(":last-child")) {
// here is many method to get firstChild from current
return $currentLi.parent().first();
}
return $currentLi.next("li");
}
function prevLi($currentLi){
if ($currentLi.is(":first-child")) {
// here is many method to get lastChild from current
return $currentLi.parent().last();
}
return $currentLi.prev("li");
}
function nextImageFunction() {
$("#next").click(function () {
var $currentLy = $("li.start");
nextLi($currentLy).addClass("start");
$currentLy.removeClass("start");
var src = $currentLy.find("img").attr('src');
src = avoidSrcSymbols(src);
changeImage($(".container2"), src);
});
}
function previousImageFunction() {
$("#prev").click(function () {
var $currentLy = $("li.start");
prevLi($currentLy).addClass("start");
$currentLy.removeClass("start"); // remove Class from currect li
var src = $currentLy.find("img").attr('src');
src = avoidSrcSymbols(src);
changeImage($(".container2"), src);
});
}