How can I declare my JS functions as jQuery functions?
My code is working but I want have only jQuery with no vanilla JS.
I know that is no point of doing this but I need to have only jQuery and no pure JavaScript.
Thanks for your help.
var slideOne = ["assets/slider-image-7.jpg", "assets/slider-image-6.jpg", "assets/slider-image-9.jpg", "assets/slider-image-8.jpg", "assets/slider-image-5.jpg"];
var slideTwo = ["assets/slider-image-4.jpg", "assets/slider-image-1.jpg", "assets/slider-image-2.jpg", "assets/slider-image-3.jpg"];
var firstSlide = document.querySelector(".first");
var secondSlide = document.querySelector(".second");
function rowOne() {
for (var i = 0; i < slideOne.length; i++) {
var picture = document.createElement("li");
picture.classList.add("picture");
picture.innerHTML = '<img src="' + slideOne[i] + '"/>';
firstSlide.appendChild(picture);
}
}
function rowTwo() {
for (var i = 0; i < slideTwo.length; i++) {
var picture = document.createElement("li");
picture.classList.add("picture");
picture.innerHTML = '<img src="' + slideTwo[i] + '"/>';
secondSlide.appendChild(picture);
}
}
function moveLeftFirst() {
$("ul.first > li:last-child").remove().prependTo(".first");
}
function moveRightFirst() {
$("ul.first > li:first-child").remove().appendTo(".first");
}
function moveLeftSecond() {
$("ul.second > li:last-child").remove().prependTo(".second");
}
function moveRightSecond() {
$("ul.second > li:first-child").remove().appendTo(".second");
}
$(".previous").click(function () {
moveLeftFirst();
moveLeftSecond();
});
$(".next").click(function () {
moveRightFirst();
moveRightSecond();
});
rowOne();
rowTwo();
const rowImages = ($el, images) =>$el.append(images.map(src => $("<li>", {
class: `picture`,
html: `<img src="${src}">`
})));
const move = ($el, isNext) => $el.find(`li:${isNext ? "first" : "last"}-child`).remove()[isNext ? 'appendTo' : 'prependTo']($el);
const $firstSlide = $(".first");
const $secondSlide = $(".second");
$(".previous, .next").on("click", function () {
const isNext = $(this).is('.next');
move($firstSlide, isNext);
move($secondSlide, isNext);
});
rowImages($firstSlide, ["//placehold.it/50x50/0bf", "//placehold.it/50x50/f0b", "//placehold.it/50x50/fb0", "//placehold.it/50x50/bf0", "//placehold.it/50x50/0fb"]);
rowImages($secondSlide, ["//placehold.it/50x50/fb0", "//placehold.it/50x50/0bf", "//placehold.it/50x50/0fb" ,"//placehold.it/50x50/f0b", "//placehold.it/50x50/bf0"]);
ul {padding:0; list-style:none; display:flex; }
<ul class="first"></ul>
<ul class="second"></ul>
<button class="previous">PREV</button>
<button class="next">NEXT</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
You could replace the following syntax:
document.querySelector with $
document.createElement('li') with $('<li></li>')
classList.add with addClass
innerHTML with html
appendChild with append
So the final result will be:
var slideOne = ["assets/slider-image-7.jpg", "assets/slider-image-6.jpg", "assets/slider-image-9.jpg", "assets/slider-image-8.jpg", "assets/slider-image-5.jpg"];
var slideTwo = ["assets/slider-image-4.jpg", "assets/slider-image-1.jpg", "assets/slider-image-2.jpg", "assets/slider-image-3.jpg"];
var firstSlide = $(".first");
var secondSlide = $(".second");
function rowOne() {
for (var i = 0; i < slideOne.length; i++) {
var picture = $("<li>")
.addClass("picture")
.html('<img src="' + slideOne[i] + '"/>');
firstSlide.append(picture);
}
}
function rowTwo() {
for (var i = 0; i < slideTwo.length; i++) {
var picture = $("<li></li>")
.addClass("picture")
.html('<img src="' + slideTwo[i] + '"/>');
secondSlide.append(picture);
}
}
function moveLeftFirst() {
$("ul.first > li:last-child").remove().prependTo(".first");
}
function moveRightFirst() {
$("ul.first > li:first-child").remove().appendTo(".first");
}
function moveLeftSecond() {
$("ul.second > li:last-child").remove().prependTo(".second");
}
function moveRightSecond() {
$("ul.second > li:first-child").remove().appendTo(".second");
}
$(".previous").click(function () {
moveLeftFirst();
moveLeftSecond();
});
$(".next").click(function () {
moveRightFirst();
moveRightSecond();
});
rowOne();
rowTwo();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Related
I Am Trying to make a popover with a bootstrap carousel and where the carousel items are to be generated and appended from a script but I get the carousel but I am unable to append the item. I tried hard but I didn't come up with a solution.
the HTML initialized is as below
HTML:
<div class="popup" data-popup="popup-1">
<div class="popup-inner">
<i class="fas fa-bars"></i>
<div class="frame">
<div id='carousel' class='carousel slide' data-bs-ride='carousel'>
<div class='carousel-inner items-slider1'>
</div>
</div>
</div>
</div>
</div>
the script I have tried was
Javascript:
function findallchord(currentchord , currenttype) {
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord ,currenttype,i)) {
Raphael.chord("div3", Raphael.chord.find(currentchord , currenttype,i), currentchord +' ' +currenttype).element.setSize(75, 75);
}
}
}
var getChordRoots = function (input) {
if (input.length > 1 && (input.charAt(1) == "b" || input.charAt(1) == "#"))
return input.substr(0, 2);
else
return input.substr(0, 1);
};
$('.popup').on('shown.bs.popover', function () {
$('.carousel-inner').carousel();
});
$('[data-bs-toggle="popover"]').popover({
html: true,
content: function() {
return $('.popup').html();
}}).click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
});
I have also tried appendTo also as
$(theDiv).appendTo('.items-slider1');
Please Help to solve this
This is the output I get, the appended elements are not in the carousel
Note: I am using Bootstrap 5
Try instantiating the carousel after you've set it up
/*
$('.popup').on('shown.bs.popover', function () {
$('.carousel-inner').carousel();
});
*/
$('[data-bs-toggle="popover"]').popover({
html: true,
content: function() {
return $('.popup').html();
}}).click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
$('.carousel-inner').carousel();
});
It was needed to do call the click function first before popover as below
$('[data-bs-toggle="popover"]').click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
}).popover({
html: true,
content: function() {
return $('.popup').html();
}});
I am trying to change one image source with id using javascript, also I would like to add/remove width to the picture depending on whether we click on + or - button.
var changeimg = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.src == "images/soleil.jpg") {
sun_to_eclipse.src = "images/eclipse.jpg";
} else {
sun_to_eclipse.src = "images/soleil.jpg";
}
}
var addpx = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.width <= "500") {
sun_to_eclipse.style.width = sun_to_eclipse.style.width + "20px"
}
}
var removepx = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.width >= "250") {
sun_to_eclipse.style.width = sun_to_eclipse.style.width - "20px"
}
}
var setupListeners = function() {
var plus = document.getElementById("plus");
var minus = document.getElementById("minus");
var sun_to_eclipse = document.getElementById("sun");
sun_to_eclipse.addEventListener("click", changeimg);
plus.addEventListener("click", addpx);
minus.addEventListener("click", removepx);
}
window.addEventListener("load", setupListeners);
<div id="doc">
<div id="buttons">
<button id="plus">+</button>
<button id="minus">-</button>
</div>
<img id="sun" src="https://pbs.twimg.com/profile_images/641353910561566720/VSxsyxs7_400x400.jpg" alt="sunny" />
</div>
Any idea what's wrong?
To Fetch the Width use .clientWidth instead of .style.width
So for addpx use sun_to_eclipse.clientWidth + 20 + "px"; and
for minus use sun_to_eclipse.clientWidth - 20 + "px";
var changeimg = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.src == "https://camo.githubusercontent.com/e9c5fe6cb160f55f564723b8c1679170c74f5e53/687474703a2f2f73392e706f7374696d672e6f72672f7a336e707077797a332f73686565705f333530782e6a7067") {
sun_to_eclipse.src = "http://www.ptahai.com/wp-content/uploads/2016/06/Best-Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg";
} else {
sun_to_eclipse.src = "https://camo.githubusercontent.com/e9c5fe6cb160f55f564723b8c1679170c74f5e53/687474703a2f2f73392e706f7374696d672e6f72672f7a336e707077797a332f73686565705f333530782e6a7067";
}
}
var addpx = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.clientWidth <= "500") {
sun_to_eclipse.style.width = sun_to_eclipse.clientWidth + 20 + "px";
}
}
var removepx = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.clientWidth >= "250") {
sun_to_eclipse.style.width = sun_to_eclipse.clientWidth - 20 + "px";
}
}
var setupListeners = function() {
var plus = document.getElementById("plus");
var minus = document.getElementById("minus");
var sun_to_eclipse = document.getElementById("sun");
sun_to_eclipse.addEventListener("click", changeimg);
plus.addEventListener("click", addpx);
minus.addEventListener("click", removepx);
}
window.addEventListener("click", setupListeners);
#sun {
width: 300px;
}
<div id="doc">
<div id="buttons">
<button id="plus">+</button>
<button id="minus">-</button>
</div>
<img id="sun" src="https://cdn.pixabay.com/photo/2018/03/11/20/42/mammals-3218028_1280.jpg" alt="sunny" />
</div>
the problem is with your setting widths. style.width will return text with some number plus the unit at the end. use offsetWidth property.
var sun = false;
var changeimg = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun == false) {
sun_to_eclipse.src = "images/eclipse.jpg";
sun = true;
} else {
sun_to_eclipse.src = "images/soleil.jpg";
sun = false;
}
}
var addpx = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.width <= "500") {
sun_to_eclipse.style.width = sun_to_eclipse.offsetWidth + 20 + "px"
}
}
var removepx = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.width >= "250") {
sun_to_eclipse.style.width = sun_to_eclipse.offsetWidth - 20 + "px"
}
}
var setupListeners = function() {
var plus = document.getElementById("plus");
var minus = document.getElementById("minus");
var sun_to_eclipse = document.getElementById("sun");
sun_to_eclipse.addEventListener("click", changeimg);
plus.addEventListener("click", addpx);
minus.addEventListener("click", removepx);
}
window.addEventListener("load", setupListeners);
<div id="doc">
<div id="buttons">
<button id="plus">+</button>
<button id="minus">-</button>
</div>
<img id="sun" src="https://pbs.twimg.com/profile_images/641353910561566720/VSxsyxs7_400x400.jpg" alt="sunny" />
</div>
IMAGE ONCLICK: its not working properly because img.src contains the full address to the image. eg
document.getElementById("sun").src;
"file:///C:/Users/Abhinav/Desktop/images/soleil.jpg"
you can fix that using a variable
var sun = false;
var changeimg = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun == false) {
sun_to_eclipse.src = "images/eclipse.jpg";
sun = true;
} else {
sun_to_eclipse.src = "images/soleil.jpg";
sun = false;
}
}
Making use of offsetWidth to achieve this.
var changeimg = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.src == "images/soleil.jpg") {
sun_to_eclipse.src = "images/eclipse.jpg";
} else {
sun_to_eclipse.src = "images/soleil.jpg";
}
}
var addpx = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.width <= "500") {
sun_to_eclipse.style.width = sun_to_eclipse.offsetWidth + 20 + "px"
}
}
var removepx = function() {
var sun_to_eclipse = document.getElementById("sun");
if (sun_to_eclipse.width >= "250") {
sun_to_eclipse.style.width = sun_to_eclipse.offsetWidth - 20 + "px"
}
}
var setupListeners = function() {
var plus = document.getElementById("plus");
var minus = document.getElementById("minus");
var sun_to_eclipse = document.getElementById("sun");
sun_to_eclipse.addEventListener("click", changeimg);
plus.addEventListener("click", addpx);
minus.addEventListener("click", removepx);
}
window.addEventListener("load", setupListeners);
<div id="doc">
<div id="buttons">
<button id="plus" onClick =>+</button>
<button id="minus">-</button>
</div>
<img id="sun" src="https://pbs.twimg.com/profile_images/641353910561566720/VSxsyxs7_400x400.jpg" alt="sunny" />
</div>
i have an array in java script, that array have file name and file path, now i have to assign that array in php and upload that file which are store in array, what can i do please give me solutions.
This is my javascript
<script type="text/javascript">
var arrImgNPath = [];
var arrUniqueIds = [];
function myFunction() {
var files = $('#filesID').prop("files");
var names = $.map(files, function(val) { return val.name; });
console.log(names);
console.log("N the final result is :");
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
//$('#str').val(JSON.stringify(dict));
console.log("obj value :",dict);
}
}
function removeImageDataFromArray(spanId){
console.log("spanID--------------------------------------"+spanId);
arrImgNPath= arrImgNPath.filter(function(el) { return el.ID != spanId; });
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
console.log("obj value :",dict);
}
}
function uniqId() {
while (1) {
var uid = Math.round(new Date().getTime() + (Math.random() * 100));
var isPresent = false;
for(var i=0; i<arrUniqueIds.length; i++){
var idFromArray = arrUniqueIds[i];
if (uid == idFromArray){
isPresent = true;
}
}
if (isPresent === false) {
return uid;
}
}
}
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#filesID").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
//console.log(files);
var filePath = $(this).val();
//console.log("fake pathddddddddddd"+filePath);
for (var i = 0; i < filesLength; i++) {
var tmppath = URL.createObjectURL(event.target.files[0]);
filePath =tmppath;
var f = files[i];
var randomId = uniqId();
var dict = {};
dict.name = f.name;
dict.path = filePath;
dict.ID = randomId;
arrImgNPath[arrImgNPath.length] = dict;
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
//console.log("bfsd dsf sdfdsfds"+e.target.result);
// console.log("adsfdsfsd fsdf sdfsdfsdfsdsdfd"+randomId);
$("<span id=\"" + randomId + "\" class=\"pip\" >" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#filesID");
$(".remove").click(function(){
//$(this).find("span").attr("id", "myspan_"+i);
console.log("files id values :"+ $(this).parent(".pip").attr("id"));
removeImageDataFromArray($(this).parent(".pip").attr("id"));
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API");
}
});
</script>
dict is my array how can assign that array in php and upload in file,
you can check in console to gat the value
php file
<!DOCTYPE html>
<head>
<style>
input[type="file"] {
display: block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
padding: 1px;
cursor: pointer;
}
.pip {
display: inline-block;
margin: 10px 10px 0 0;
}
.remove {
display: block;
background: #444;
border: 1px solid black;
color: white;
text-align: center;
cursor: pointer;
}
.remove:hover {
background: white;
color: black;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field" align="left">
<form method="post" enctype="multipart/form-data" >
<h3>Upload your images</h3>
<input type="file" id="filesID" name="files[]" size="150" multiple="multiple" >
<input type="submit" name="submit" >
<input type="button" onclick="myFunction()" value="clickMe">
</form>
</div>
whenever click the clickMe button you can the file name and file path in console check it and please help me
Sorry for the late return. I am not 100% sure if this is what you wanted. But i did it anyway :). Thanks to #Ben_Lee with his answer I managed to wrap the initiation inside a function.
var arrImgNPath = [];
var arrUniqueIds = [];
function myFunction() {
var files = $('#filesID').prop("files");
var names = $.map(files, function(val) { return val.name; });
console.log(names);
console.log("N the final result is :");
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
//$('#str').val(JSON.stringify(dict));
console.log("obj value :",dict);
}
}
function removeImageDataFromArray(spanId){
console.log("spanID--------------------------------------"+spanId);
arrImgNPath= arrImgNPath.filter(function(el) { return el.ID != spanId; });
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
console.log("obj value :",dict);
}
}
function uniqId() {
while (1) {
var uid = Math.round(new Date().getTime() + (Math.random() * 100));
var isPresent = false;
for(var i=0; i<arrUniqueIds.length; i++){
var idFromArray = arrUniqueIds[i];
if (uid == idFromArray){
isPresent = true;
}
}
if (isPresent === false) {
return uid;
}
}
}
function initiateFiles(file) {
var tmppath = URL.createObjectURL(event.target.files[0]);
filePath =tmppath;
var f = file;
var randomId = uniqId();
var dict = {};
dict.name = f.name;
dict.path = filePath;
dict.ID = randomId;
arrImgNPath[arrImgNPath.length] = dict;
var fileReader = new FileReader();
fileReader.onload = (function(e) {
//var file = e.target;
//console.log("bfsd dsf sdfdsfds"+e.target.result);
// console.log("adsfdsfsd fsdf sdfsdfsdfsdsdfd"+randomId);
$("<span id=\"" + randomId + "\" class=\"pip\" >" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#filesID");
$(".remove").click(function(){
//$(this).find("span").attr("id", "myspan_"+i);
console.log("files id values :"+ $(this).parent(".pip").attr("id"));
removeImageDataFromArray($(this).parent(".pip").attr("id"));
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#filesID").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
var filePath = $(this).val();
for (var i = 0; i < filesLength; i++) {
initiateFiles(files[i]);
}
console.log(arrImgNPath);
var myJSON = JSON.stringify(arrImgNPath);
$("<input value=\'" + myJSON + "\' name=\"myJSON\" type=\"hidden\" />").insertAfter("#filesID");
});
} else {
alert("Your browser doesn't support to File API");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field" align="left">
<form method="post" action="yourOther.php" enctype="multipart/form-data" >
<h3>Upload your images</h3>
<input type="file" id="filesID" name="files[]" size="150" multiple="multiple" >
<input type="submit" name="submit" >
<input type="button" onclick="myFunction()" value="clickMe">
</form>
</div>
Here i created a hidden input, which stores the array.
$("<input value=\'" + myJSON + "\' name=\"myJSON\" type=\"hidden\" />").insertAfter("#filesID");
And then assigned an action to the form to send the data to another php file.
<form method="post" action="yourOther.php" enctype="multipart/form-data" >
And now it is time to get the data and process:
<?php
$data = json_decode($_POST['myJSON']);
foreach ($data as $key => $value) {
echo " Name : $value->name <hr>";
echo " Path : $value->path <hr>";
echo " ID : $value->ID <hr>";
}
?>
I hope this helps, if you have further questions, don't hesitate to ask.
So I'm trying to add an option on my options page for people to set 1-3 letters as a link to a website. Currently I'm getting a NaN value for the linkNumber when I run the function.
The Function:
function addLink () {
chrome.storage.local.get('linkNumber', function (x) {
if (x.linkNumber == undefined) {
chrome.storage.local.set({'linkNumber': '0'}, function() {
addLink();
});
} else {
var linkNumberInteger = parseInt(x.linkNumber);
var handle = document.getElementById("short");
var link = document.getElementById("long");
var handleValue = handle.value;
var linkValue = link.value;
var handleNumber = x.linkNumber + '-handle';
var urlNumber = x.linkNumber + '-link';
var objectOne = {};
var objectTwo = {};
objectOne[handleNumber] = x.linkNumber + '-handle';
objectTwo[urlNumber] = x.linkNumber + '-link';
console.log(x.linkNumber);
console.log(handleNumber);
chrome.storage.local.set({handleNumber: handleValue}, function(y) {
console.log(y.handleNumber + ' handle saved');
});
chrome.storage.local.set({urlNumber: linkValue}, function(z) {
console.log(z.handleNumber + ' link saved');
});
var linkNumberIntegerNext = linkNumberInteger++;
var n = linkNumberIntegerNext.toString();
chrome.storage.local.set({'linkNumber': n}, function() {
});
alert('Link Added');
}
});
}
The Html:
<h3 class="option">Add Quick Link:</h3>
<input contenteditable="true" type="text" class="short-quicklink" id="short" maxlength="3">
<span>http://</span><input contenteditable="true" type="text" class="long-quicklink" id="long">
<button class="add">Add Quick Link</button>
All I want to do is:
there are 7 numbers and 7 divs, they are linked to each other (nr 0 it's in a relationship with div 0)
when one of the numbers is clicked, it should collapse all the other divs which are not selected
it can be selected more at one time
To sum up, basically, the page has some labels with numbers and 7 divs which are all displayed by default (the divs), but when one or more of them are chosen by clicking on the numbers, the page should display only the chosen divs.
This is what I've been trying to do:
for(var i = 0; i <= 6; i++) {
if(i != (floors[i])) {
$("#lvl" + floors[i]).slideUp();
}
}
More code:
http://jsfiddle.net/LSjg4/
Try
var floors = [];
var $lvls = $('.lvl'), $nrs = $(".nr");
$nrs.click(function () {
var $nr = $(this), index = $nrs.index($nr), $lvl = $lvls.eq(index);
$lvl.add($nr).toggleClass('active');
if($nr.hasClass('active')){
$lvls.not('.active').slideUp();
$lvl.slideDown();
$nr.css("background-color", "#1b7664");
$nr.css("border-color", "#236959");
floors.push(($nr).text());
} else {
$nr.css("background-color", "#02c099");
$nr.css("border-color", "#13a480");
if($nrs.filter('.active').length == 0){
$lvls.slideDown();
} else {
$lvls.not('.active').slideUp();
}
var text = $nr.text();
floors.splice($.inArray(text, floors), 1);
}
console.log('floors', JSON.stringify(floors))
});
Demo: Fiddle
I corrected a few things in your code. Here is the below working code and link to it in jsfiddle.
There was a data type mismatch(comparing string and int). When matching whether it exists in floors array, the code was checking floors[i] only whereas the i can be any position in floors.
var floors = [];
$(".nr").click(function () {
var state = $(this).data('state');
state = !state;
if (state) {
$(this).css("background-color", "#1b7664");
$(this).css("border-color", "#236959");
floors.push(parseInt($(this).text()));
console.log(floors);
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
} else {
$(this).css("background-color", "#02c099");
$(this).css("border-color", "#13a480");
for (var i = 0; i < floors.length; i++) {
if (floors[i] == parseInt($(this).text()))
floors.splice(i, 1);
}
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
}
$(this).data('state', state);
});
Demo Here: http://jsfiddle.net/bFe9T/
I believe this is what you're looking for:
$(".nr").click(function () {
$(this).toggleClass('selected');
$('.nr').each(function(){
var $target = $('#lvl'+$(this).text());
if($(this).is('.selected'))
$target.slideDown();
else
$target.slideUp();
});
});
Note that instead of changing the CSS properties I set up a class for the selected elements
Demo fiddle
Try this
$(".nr").click(function () {
//alert($(this).attr("data-select"));
if($(this).attr("data-select") === "1") {
$(this).attr("data-select","0");
} else {
$(this).attr("data-select","1");
}
$(".nr").each(function(){
if($(this).attr("data-select") === "1") {
var id = $(this).text();
$("div#lvl"+id).slideDown();
} else {
var id1 = $(this).text();
$("div#lvl"+id1).slideUp();
}
});
});
FIDDLE
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>slideUp demo</title>
<style>
.norm { background:#cccccc; margin:3px; width:80px;height:40px; float:left;color:#000000 }
.faded { background:#ffffff; margin:3px; width:80px;height:40px; float:left;color:#ffffff }
.btn{width:80px;}
</style>
<script src="http://code.jquery.com/jquery-1.8.1.js"></script>
</head>
<body>
<button class="btn" onClick="show(1)">1</button>
<button class="btn" onClick="show(2)">2</button>
<button class="btn" onClick="show(3)">3</button>
<button class="btn" onClick="show(4)">4</button>
<button class="btn" onClick="reset()">Reset</button>
<div class="norm" id="slide1">1</div>
<div class="norm" id="slide2">2</div>
<div class="norm" id="slide3">3</div>
<div class="norm" id="slide4">4</div>
<div></div>
<script>
var save = new Array();
function show(indx){
if($.inArray(indx, save)==-1){
save.push(indx);
for(var i=0;i<5;i++){
if($.inArray(i, save)==-1){
$('#slide'+i).attr('class','faded');
}
else{
$('#slide'+i).attr('class','norm');
}
}
}
}
function reset(){
save = new Array();
for(var i=0;i<5;i++){
$('#slide'+i).attr('class','norm');
}
}
</script>
</body>
</html>