Hide a class from other class with the same name when clicked - javascript

An image is display to my webpage, all having the same class name.
I try hiding a particular one with it is clicked but any time I click that particular class, all the classes are affected
I used PHP to echo the image to webpage. I have tried all I could but not working.
<img class="media_image" onclick="hide()" src="media/<?php echo $media?>"/>
<script>
function hide(){
var divs = document.getElementsByClassName("media_image");
for(var i = 0; i <= divs.length; i++){
console.log("Item: ", i);
}
}
</script>

You can change onclick="hide()" to onclick="hide(this)" to pass the element into the function and then the function can be changed to accept it.
function hide (element) {
//do whatever with element
element.style.display = "none";
}

you could add a second special class to every image in the webpage like :
<img class="myimg img-1">
<img class="myimg img-2">
<img class="myimg img-3">
// ect

Related

Apply eventlistener to multiple elements based on their IDs

I have two buttons defined with their IDs : but-toggle, but-close for show hide a panel :
<button id="but-toggle">Panel</button>
<div id="main-panel" style="display:none">
<button id="but-close">X</button>
<!-- some panel data -->
</div>
Now i have a JS function which toggle the panel (show/hide) assigned to but-toggle as following :
(function(){document.getElementById("but-toggle").addEventListener("click",function(){
var pan = document.getElementById("main-panel");
if(pan.style.display==="inline-block")
{pan.style.display="none"}
else
{pan.style.display="inline-block"}
});})();
My question is how to use the same function for both buttons without writing two func, one for each.
I want a solution for elements based on their ids, since the classes are differents and can't use getElementByClass for this
Thanks
You can use document.querySelector to get a list of elements from a list of IDs:
function toggleFn() {
const pan = document.getElementById("main-panel");
if(pan.style.display === "inline-block") {
pan.style.display = "none";
} else {
pan.style.display = "inline-block";
}
}
document.querySelector("#Id1, #Id2")
.forEach(elem => elem.addEventListener(toggleFn);
You can use the below to get all buttons
var btns=document.getElementsByTagName('button');
for (let i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
//code
});
}
(OR)
if you use input tag with type button
document.querySelectorAll("input[type=button]");
(OR)
Based on multiple IDs
document.querySelectorAll('#id1, #id2, #id3');
then you can add eventListener

Swapping images back and forth on click in multiple places

I'm creating an accordion with my own arrow icons (pngs) as the "toggle" so when you click on the down red arrow, the up blue arrow will show to collapse, and vice versa.
I got it to work with the below code, but I have multiple accordions with the same arrow icons, and I need them all to do this. When I add the same code to the other accordions (even if I changed out the ID to be unique and update it in the JS), it still only wants to toggle the first accordion.
Can anyone help me get this to work across multiple image sets (but the same images)?
HTML:
<img src="/wp-content/uploads/2019/08/accordion-open.png" alt="accordion icon" id="accordion" onclick="change();"></div>
JS:
var image_tracker = 'open';
function change(){
var image = document.getElementById('accordion');
if(image_tracker=='open'){
image.src='/wp-content/uploads/2019/08/accordion-close.png';
image_tracker='close';
}
else{
image.src='/wp-content/uploads/2019/08/accordion-open.png';
image_tracker='open';
}
}
If you're assigning the listener by ID it's only going to apply to the first one. Try using a class name instead.
<html>
<body>
<img class="accordion_icon" src="/wp-content/uploads/2019/08/accordion-open.png" />
<script type="text/javascript">
var open_src = "/wp-content/uploads/2019/08/accordion-open.png";
var close_src = "/wp-content/uploads/2019/08/accordion-close.png";
let accordion_icons = document.getElementsByClassName('accordion_icon'); // get all icons img tags
for (let i = 0; i < accordion_icons.length; i++) {
const element = accordion_icons[i];
element.addEventListener('click',(event)=>{ // set listener on each one
console.log('src was: ', event.currentTarget.src);
event.currentTarget.src = (event.currentTarget.src == open_src ? close_src : open_src) // change the src to the one it currently isn't
console.log('scr is now: ', event.currentTarget.src);
});
}
</script>
</body>
</html>
An alternative method could be also this one, if you still want to keep the even handler in the HTML:
<img src="/wp-content/uploads/2019/08/accordion-open.png" alt="accordion icon" id="accordion" onclick="change(this);"></div>
And in the JS:
function change(image){
image.src = image.src.endsWith("open.png")
? image.src.replace(/open\.png$/, "close.png")
: image.src.replace(/close\.png$/, "open.png");
}

Using .getElementsByClassName to access multiple popups

I am attempting to use the following javascript to create various popups.Image popups when text is clicked. The problem is that when I click any of the text containers, all of the popup images appear. I know I am missing something obvious. Any help would be much appreciated. Here is the JS code:
function myFunction() {
var popup = document.getElementsByClassName("myPopup");
for(var i=0; i<popup.length; i++) {
popup[i].classList.toggle('show');
}
}
HTML:
<div class="popup" onclick="myFunction()"><span class="castName">Viola,</span>
<span class="popuptext myPopup"><img src=Viola_1.jpg
style="width:300px;height:100%;" alt="Viola"><p>Miss Ellen Terry as Viola, mid
to late 19th century</p></span></div>
Your function gets a list of elements and toggle the class 'show' to every element instead of the element you want. You have to pass in the element to the function.
You can change the onclick event for each div from:
<div class="popup" onclick="myFunction()">
to:
<div class="popup" onclick="myFunction(this)">
Then in your javascript
function myFunction(element){
if (element){ //If the element is passed into this function
element.getElementsByClassName("myPopup")[0].toggle('show');
}
}
Thum, this was very helpful. I ended up changing the HTML as you suggested and did the following to the javascript, which worked perfectly:
function myFunction(element) {
var popup = element.getElementsByClassName('myPopup');
var i;
for( i=0; i<popup.length; i--) {
popup[i].classList.toggle('show');
}
}

Jquery toggle img attribute

I am trying to toggle images from the thumbnail to the feature image when the thumb nail is clicked. Currently when its clicked the images will swap but I cant get them to swap back with the thumb nail is clicked on again. I've tried using toggle but when the thumb nail is clicked on it would remove the image completely and I couldnt get any image to return. Currently this will switch the images but not switch or toggle them back on click.
$(".browseTable").on('click', 'td', function () {
var thumbNail = $(this).parent('tr').find('img').attr('src');
var feature = $('#featureImg img').attr('src');
$('#featureImg img').fadeOut(400, function () {
$(this).fadeIn(400)[0].src = thumbNail;
});
});
You can use data for store source string and toggling images
preview on : https://jsfiddle.net/5kxf65Lx/
<img src="source1.jpg" data-srcfirst="source1.jpg" data-srcsecond="source2.jpg" />
<script type="text/javascript">
$('img').click(function(){
var loaded = $(this).attr('src')
var first = $(this).data('srcfirst')
var second = $(this).data('srcsecond')
if(loaded == first){
$(this).attr('src' , second)
} else {
$(this).attr('src' , first)
}
})
Try this. When the parent is clicked we toggle both children. The large version starts off hidden.
<div class="toggle js-toggle">
<img src="http://www.placehold.it/100x100" alt="" class="toggle__thumb js-toggle-image"/>
<img src="http://www.placehold.it/500x500" alt="" class="toggle__active js-toggle-image" style="display: none" />
</div>
The jQuery
$('.js-toggle').on('click', function() {
$(this).find('.js-toggle-image').toggle();
});
https://jsfiddle.net/uoLv2nkh/1/
Or an only CSS way if you only care about when the user is clicking.
https://jsfiddle.net/uoLv2nkh/
You can achieve your target via setting src of image in css.
.imageOne{
content:url(YOUR SOURCE);
}
.imageTwo{
content:url(YOUR SOURCE);
}
add class to your image element in start
check if element exist by either class if exist toggle() to another, this will change the image back to another.
And use toggle() like following example
$(".browseTable").on('click', 'td', function () {
//var thumbNail = $(this).parent('tr').find('img').attr('src');
//var feature = $('#featureImg img').attr('src');
//$('#featureImg img').fadeOut(400, function () {
// $(this).fadeIn(400)[0].src = thumbNail;
//});
$('#featureImg img').find('.imageOne, .imageTwo').toggle();
});
I am able to use toggle simply to change one element to another. etc. hope it will help you.
Is it possible to set the equivalent of a src attribute of an img tag in CSS?

Javascript - selecting and .click()

I'm trying to automate a click when visting a website. This is the HTML I'm looking at.
<div class="box_wrapper">
<a id="itemcode_11094414" class="box">7.5</a>
<a id="itemcode_11094415" class="box">8</a>
<a id="itemcode_11094416" class="box">8.5</a>
</div>
when I select the size, say for instance size 8, the class= tag turns to "box active" like so,
<div class="box_wrapper">
<a id="itemcode_11094414" class="box">7.5</a>
<a id="itemcode_11094415" class="box active">8</a>
<a id="itemcode_11094416" class="box">8.5</a>
</div>
How can I go loop through the class and select a desired size? Also, I was just tinkering around and noticed that I had a hard time simulating a click on the add to cart and other buttons. For the add to cart the HTML looks like this,
<div class="add_to_cart">
<div class="add_to_cart_left">
<img id="add_to_bag_btn" alt="Add To Bag" src="/images/add_to_bag.gif"></img>
<img id="add_to_bag_btn_processing" alt="" src="/images/add_to_bag_processing.gif"></img>
</div>
</div>
Is this the correct chunk of HTML I should be looking at for a simulation of a click?
Since it's Christmas and you sounded excited to see jQuery in action I created a fiddle for you. Here is a sample of what you (could) want using jQuery: http://jsfiddle.net/akkJ5/2/
The code for selecting sizes and twiddling active classes is as follows:
var selectedSize = '';
$(".box").click(function(){
$(".box").removeClass('active');
$(this).addClass('active');
selectedSize = $(this).html();
$("#messages").html(selectedSize +" was selected");
});
In it I create an event listener for clicks on all box class elements. Since only one should be active I remove the active class from all box class elements then add active to the clicked box. I save the innerHTML of the selected link as selectedSize, and write it to an element for display sake.
In terms of simulating a click on a button you could do something like this:
$(".add_to_cart").click(function(){
alert('cart clicked');
});
$(".add_to_cart").trigger('click');
Updated
To attach event to all the classed you can do
var selectedvalue = '';
for(var i = 0; i < document.getElementsByClassName('box').length; i++ ) {
var d = document.getElementsByClassName('box')[i];
d.onclick = function (e) {
selectedvalue = this.text;
this.className = this.className + " active";
}
}
Check http://jsfiddle.net/raunakkathuria/Nv8t2/2/
To navigate through classes and add your class to the link that has same value
JS
var value = 8;
for(var i = 0; i < document.getElementsByClassName('box').length; i++ ) {
var d = document.getElementsByClassName('box')[i];
if(d.text == value) {
d.className = d.className + " active";
}
}
To simulate the click handler for the add to cart you can enclose them to
<a href="javascript:void(0)" onclick="myJsFunc();">
<img id="add_to_bag_btn" alt="Add To Bag" src="/images/add_to_bag.gif"></img>
</a>
If you want to send it some link update this href="javascript:void(0)" onclick="myJsFunc();" to href="your_link"
Check http://jsfiddle.net/raunakkathuria/Nv8t2/1/

Categories