I need a button called #btn-limone to remove filter: "grayscale(100%)" on first click and on the second click to restore it. I need it to be done through styles and not classes. How can I do this?
jQuery("#btn-limone").on("click", function () {
jQuery("#agrumi_box, #frutta_polpa_bianca_box, #limone_box").removeAttr("style");
});
With this I can remove the style but I would like that at the second click it would be brought back to 100%.
Thank you to anyone who wants to help me
You can check it has style attribute or not, if id doesn't have you can add your style, if it has style you can remove it. like this:
const items = $('.item');
function toggleFilter(button, relevantIndexes) {
const toggleOn = button.attr('data-toggle') == 'on'
button.attr('data-toggle', toggleOn ? 'off' : 'on')
$.each(items, function(index, item) {
if (!relevantIndexes.includes(index)) return;
const style = item.getAttribute('style');
if (toggleOn) {
item.removeAttribute('style');
} else {
item.setAttribute('style', 'filter:grayscale(100%)');
}
});
}
$('#btn-limone').on('click', function() {
const relevantIndexes = [0, 1, 3];
toggleFilter($(this), relevantIndexes);
});
$('#btn-lime').on('click', function() {
const relevantIndexes = [1, 2, 3];
toggleFilter($(this), relevantIndexes);
});
.item {
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div class="item">
<img src="https://fakeimg.pl/200x100/a10000/?text=Lemone" />
</div>
<div class="item">
<img src="https://fakeimg.pl/200x100/a10000/?text=Lemone-Lime" />
</div>
<div class="item">
<img src="https://fakeimg.pl/200x100/a10000/?text=Lime" />
</div>
<div class="item">
<img src="https://fakeimg.pl/200x100/a10000/?text=Lemone-Lime" />
</div>
</div>
<button class="btn" id="btn-limone" data-toggle="off">Limone</button>
<button class="btn" id="btn-lime" data-toggle="off">Lime</button>
Related
I'm learning JavaScript and this is a practice scenario for me.
What I have already is a button that clones content, and within that content that has been cloned, there is a button to remove it.
When I click the button that prompts you to remove the content, it removes the first set of content.
What I want to happen is when you click the button that prompts you to remove the content, it removes the content related to that button and nothing else.
This is the CodePen link.
https://codepen.io/JosephChunta/pen/YzwwgvQ
Here is the code.
function addContent() {
var itm = document.getElementById("newContent");
var cln = itm.cloneNode(true);
document.getElementById("placeToStoreContent").appendChild(cln);
}
function removeContent() {
var x = document.getElementById("content").parentNode.remove();
}
// This is for debug purposes to see which content is which
document.getElementById('orderContent')
.addEventListener('click', function(e) {
const orderedNumber = document.querySelectorAll('.thisIsContent');
let i = 1;
for (p of orderedNumber) {
p.innerText = '' + (i++);
}
});
.contentThatShouldBeHidden {
display: none;
}
<div id="placeToStoreContent">
</div>
<button id="orderContent" onclick="addContent()">Add Content</button>
<div class="contentThatShouldBeHidden">
<div id="newContent">
<div id="content">
<p class="thisIsContent">This is a prompt</p>
<button onclick="removeContent()">Remove this</button>
<hr />
</div>
</div>
</div>
When you'r trying to remove by ID, it takes the first ID it finds.
To remove the correct content, send this onclick.
<button onclick="removeContent(this)">Remove this</button>
And handle it in your function:
function removeContent(el) {
el.parentNode.remove();
}
Example:
function addContent() {
var itm = document.getElementById("newContent");
var cln = itm.cloneNode(true);
document.getElementById("placeToStoreContent").appendChild(cln);
}
function removeContent(el) {
el.parentNode.remove();
}
// This is for debug purposes to see which content is which
document.getElementById('orderContent')
.addEventListener('click', function(e) {
const orderedNumber = document.querySelectorAll('.thisIsContent');
let i = 1;
for (p of orderedNumber) {
p.innerText = '' + (i++);
}
});
.contentThatShouldBeHidden { display: none; }
<div id="placeToStoreContent">
</div>
<button id="orderContent" onclick="addContent()">Add Content</button>
<div class="contentThatShouldBeHidden">
<div id="newContent">
<div id="content">
<p class="thisIsContent">This is a prompt</p>
<button onclick="removeContent(this)">Remove this</button>
<hr />
</div>
</div>
</div>
In your remove button, do this:
<!-- The "this" keyword is a reference to the button element itself -->
<button onclick="removeContent(this)">Remove this</button>
And in your javascript:
function removeContent(element) {
element.parentNode.remove();
}
I'm trying to add a Class to an img when the mouse is over an element and remove the class when the mouse is no longer over the element. I'm using object literal notation. I can't see to select the correct image, can anyone see where i'm going wrong?
let Cc = {
bindEvent: function() {
$('.title.em-below').hover( function() {
let selectedtitle = $(this);
Cc.scaleThumbnail(selectedtitle);
})
},
scaleThumbnail: function(selectedtitle) {
let $thumbnail = selectedtitle.siblings('.image-thumbnail')
let img = $thumbnail.children('img');
console.log(img);
img.addClass('thumbnail-active');
img.removeClass('thumbnail-active');
},
}
.thumbnail-active {
transform: scale(1.1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="title em-below">
Title
</div>
<a class="image-thumbnail">
<div class="wide-thumbnail em-below">
<img src="https://via.placeholder.com/350x150"/>
</div>
</a>
</div>
You need to call CC.bindEvent() to bind the event handler. And your hover function needs to toggle the class, not add it and then immediately remove it.
The img element is not a child of $thumbnail, it's the grandchild. Use .find() instead of .children().
let Cc = {
bindEvent: function() {
$('.title.em-below').hover( function() {
let selectedtitle = $(this);
Cc.scaleThumbnail(selectedtitle);
})
},
scaleThumbnail: function(selectedtitle) {
let $thumbnail = selectedtitle.siblings('.image-thumbnail')
let img = $thumbnail.find('img');
//console.log(img.attr('src'));
img.toggleClass('thumbnail-active');
},
}
Cc.bindEvent();
.thumbnail-active {
transform: scale(1.1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="title em-below">
Title
</div>
<a class="image-thumbnail">
<div class="wide-thumbnail em-below">
<img src="https://via.placeholder.com/350x150"/>
</div>
</a>
</div>
The problem is with this line, because of which the img tag is not captured.
$thumbnail.children('img');
.children only traverses its immediate child which is .wide-thumbnail.em-below.
Use .find instead
$thumbnail.find('img');
I have a series of images and I want to insert their src values and then add some div elements too associated with it into the array into the array on a click on the image and remove them if we click again.
Trying the following but I got the logic wrong as it is not removing the already el:
HTML
<div class="card">
<img src="test_2.jpg">
</div>
<div class="card">
<img src="test_2.jpg">
</div>
<div class="card">
<img src="test_3.jpg">
</div>
JS
$('body').on('click', '.card img', function () {
var urls = [];
if($(this).hasClass("checked")) {
$(this).removeClass("checked");
var urlInArray = $(this).attr('src');
urls.splice($.inArray(urlInArray, urls), 1);
console.log(urls);
} else {
$(this).addClass("checked");
var checkedItems = $('.checked'); // get the checked items
checkedItems.each(function () {
urls.push($(this).attr('src'));
});
var str = '';
urls.forEach(function (url) {
str += '<div class="card"><img class="img-fluid" onerror="this.parentNode.removeChild(this);" src="' + url + '"></div>';
});
console.log(urls);
}
});
You can use splice() to remove url from array and indexOf() to get index of that url.
var urls = [];
$(".card img").click(function() {
var src = $(this).attr('src')
$(this).hasClass('checked') ? urls.splice(urls.indexOf(src), 1) : urls.push(src);
$(this).toggleClass('checked')
console.log(urls)
})
.checked {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<img src="test_1.jpg">
</div>
<div class="card">
<img src="test_2.jpg">
</div>
<div class="card">
<img src="test_3.jpg">
</div>
That's an overkill of bytes. Use simple indexOf to check if image is already in urls. I don't see how checked on img tag is semantic, perhaps switch to data-checked?
var urls = [];
$('body').on('click', '.card img', function () {
// src; unique
var src = $(this).attr('src'),
// index of src key
index = urls.indexOf(src);
// if element exists;
if(index >= 0){
// remove
urls.splice(index, 1);
} else {
// add to urls
urls.push(src);
}
console.log(urls);
});
div {
display:inline-block
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="card">
<img src="https://source.unsplash.com/uK9QFr3fFk0/100x100">
</div>
<div class="card">
<img src="https://source.unsplash.com/pHANr-CpbYM/100x100">
</div>
<div class="card">
<img src="https://source.unsplash.com/39-0VXkvcbw/100x100">
</div>
It should be very simple. check this
$(document).ready(function () {
var status = {};
$('body').on('click', '.card img', function () {
var src = $(this).attr('src');
if (typeof status[src] == 'undefined' || status[src] == false) {
status[src] = true;
$(this).next().html('added');
} else {
status[src] = false;
$(this).next().html('removed');
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<img src="france_fan.jpg" alt='image_1'>
<span>removed</span>
</div>
<div class="card">
<img src="italy-s.gif" alt='image2'>
<span>removed</span>
</div>
<div class="card">
<img src="bangladesh-s.gif" alt='image3'>
<span>removed</span>
</div>
I have 10 different buttons and i want to show a hidden div exactly down from the button the user pressed.the div is currenlty showing exactly at the block the code of div is istead of taking new cords top: left:
THE function call:
<img style="position:relative;float:right;padding-top:7px;" onclick="find_pos(this)" src="images/view_comments.png"></li></a>
function find_pos(ele) {
var x=0;
var y=0;
while(true){
x += ele.offsetLeft;
y += ele.offsetTop;
if(ele.offsetParent === null){
break;
}
ele = ele.offsetParent;
}
hidden_comment_form.style.display='block';
hidden_comment_form.style.top=y;
hidden_comment_form.style.left=x;
}
I give you 2 options :
option 1 :
<div class="main">
<button class="btn">a</button>
<div class="toggle"> a toggle this </div>
</div>
<div class="main">
<button class="btn">b</button>
<div class="toggle"> b toggle this </div>
</div>
<script>
$(document).ready(function() {
$('button.btn').on('click', function() {
var $div = $(this).siblings('.toggle');
$div.toggle();
})
})
</script>
option 2:
<button class="btn">a</button>
<div class="toggle"> a toggle this </div>
<button class="btn">b</button>
<div class="toggle"> b toggle this </div>
<script>
$(document).ready(function() {
$('button.btn').on('click', function() {
var $div = $(this).next();
$div.toggle();
})
})
</script>
i suggest option 1 is better
An update to before, here's what I'm dealing with:
<body>
<div class="header"> <img class="imgLogo" src="img/vegtablelogo.jpg"> </div>
<div id="thumbsContainer">
<div class="thumb" id="carrotThumb"> <img id="showCarrot" class="imgThumb" src="img/carot.jpg" onClick=setupVeg("showCarrot", "carrotBig") /> </div>
<div class="hidden" id="carrotBig"> <img class="imgBig" src="img/carot.jpg" /> </div>
<div class="thumb" id="brocThumb"> <img id="showBroc" class="imgThumb" src="img/brocoli.jpg" onClick=setupVeg("showBroc", "brocBig") /> </div>
<div class="hidden" id="brocBig"> <img class="imgBig" src="img/brocoli.jpg" /> </div>
</div>
<!-- end thumbs container -->
<script>
var active = "";
function setupVeg(thumbVeg, hiddenVeg) {
$("#" + thumbVeg).click(function() {
if (active != hiddenVeg) {
$("div.hidden").hide("fast");
$("#" + hiddenVeg).show("fast", function() {});
active = hiddenVeg;
}
else {
$("div.hidden").hide("fast");
active="";
}
});
}
$("div.hidden").click(function () {
$("div.hidden").hide("fast");
isAnyBig=false;
});
</script>
</body>
This code is not working unfortunately. I have borrowed from suggested solution below.
Would be nice if it did work!
Any suggestions, most welcome.
I don't think you need any of the flags or the if conditions really. I think your logic is:
toggle carrotBig whenever showCarrot
is clicked.
hide div.hidden whenever showCarrot is clicked.
So all you need is:
$("#showCarrot").click(function () {
$("#carrotBig").toggle("fast");
$("#div.hidden").hide();
});
.toggle will handle one of your flags (isCarrotBig) and .hide() won't do anything if div.hidden is already hidden, so that takes care of your isAnyBig flag.
Now.. let's make that work with broc as well...
function setupVegetable(showId, toggleId) {
$("#" + showId).click(function () {
$("#" + toggleId).toggle("fast");
$("#div.hidden").hide();
});
}
setupVegetable("showCarrot", "carrotBig");
setupVegetable("showBroc", "brocBig");
If you're interested, you can refactor it FURTHER so you don't need to supply the IDs for each of the vegetables. I'll need to see your HTML markup though.
Ok I'll post a new answer in response to the edit.
Points worth noting:
Removed divs surrounding the imgs - they are unnecessary and complicate the relationship between the thumnnails and the large images.
Removed onclick attribute from within HTML - you will be attaching the event handlers in the JS so this is not needed.
Since the relationship between the thumbnails and the large images is quite obvious (the large images is just the next element) you don't need IDs to identify ANY of them. All you need is a class on the thumbnails.
Since we're not using IDs, only classes, you can add as many vegetables as you want without touching the JS
Your code modified:
<body>
<div class="header"> <img class="imgLogo" src="img/vegtablelogo.jpg"> </div>
<div id="thumbsContainer">
<img class="imgThumb" src="img/carot.jpg" />
<img class="imgBig hidden" src="img/carot.jpg" />
<img class="imgThumb" src="img/brocoli.jpg" />
<img class="imgBig hidden" src="img/brocoli.jpg" />
</div>
<!-- end thumbs container -->
<script>
$("#thumbsContainer .imgThumb").click(function () {
var thisImgBig = $(this).next();
// Hide all imgBigs, except for this one
$("#thumbsContainer .imgBig").not(thisImgBig[0]).hide();
// Toggle this imgBig
thisImgBig.toggle();
});
$("#thumbsContainer .imgBig").click(function () {
// Hide this imgBig
$(this).hide();
});
</script>
</body>
create a function and reuse it....something like:
/**
* document here....
*/
var toggleElements = function() {
// your code here
}
and then
$("#whatever").click(toggleElements);
Personally I would suggest creating a simple jQuery plugin. Something like so:
(function($){
$.fn.big = function(options) {
var defaults = {
target: '#carrotBig',
};
var options = $.extend(defaults, options);
return this.each(function() {
$(this).click(function () {
isBrocBig=false;
if (isCarrotBig == false && isAnyBig == false) {
$(options.target).show("fast", function() {});
isCarrotBig=true;
isAnyBig=true;
}
else if (isCarrotBig == true) {
$(options.target).hide("fast");
isCarrotBig=false;
isAnyBig=false;
}
else if (isCarrotBig == false && isAnyBig == true) {
$("div.hidden").hide("fast");
$(options.target).show("fast", function() {});
isCarrotBig=true;
}
else {
$("div.hidden").hide("fast");
isCarrotBig=false;
isAnyBig=false;
}
});
});
};
})(jQuery);
Then you just call it with something like so:
$("#showCarrot").big({target: '#carrotBig'})
Your next step should be to investigate whether you can get rid of the global variables or not.
Ok I have found a neat(ish) sollution, dependent on each hidden DIV being the .next() one. If it isn't it won't work but should be fine generally though. Hacked!
<div class="header"> <img class="imgLogo" src="img/vegtablelogo.jpg"> </div>
<div id="thumbsContainer">
<div class="thumb" id="carrotThumb"> <img id="showCarrot" class="imgThumb" src="img/carot.jpg" /> </div>
<div class="hidden" id="carrotBig"> <img class="imgBig" src="img/carot.jpg" /> </div>
<div class="thumb" id="brocThumb"> <img id="showBroc" class="imgThumb" src="img/brocoli.jpg" /> </div>
<div class="hidden" id="brocBig"> <img class="imgBig" src="img/brocoli.jpg" /> </div>
</div>
<!-- end thumbs container -->
<script>
var active = "";
$("div.thumb").click(function() {
var thumbVeg = $(this).attr("id");
var hiddenVeg = $(this).next().attr("id");
setupVeg(thumbVeg, hiddenVeg);
});
function setupVeg(thumbVeg, hiddenVeg) {
if (active != hiddenVeg) {
$("div.hidden").hide("fast");
$("#" + hiddenVeg).show("fast", function() {});
active = hiddenVeg;
}
else {
$("div.hidden").hide("fast");
active="";
}
}
$("div.hidden").click(function () {
$("div.hidden").hide("fast");
});
</script>