Implementing dynamic selectors and showing up corresponding image - javascript

I'm trying to implement a functionality:
Show list of items on the left
Dynamic selector loop each item (dashed rectangle in the image below)
On the right it should show an image for an item that has selector on it
Items' names and images will be pulled out from a storage
Question: Is this something that can be implemented with jQuery or something else?
It'd helpful if could recommend any related resources.

You can make use of this code. Replace the id's and class names with your ones.
var list = ["cat","dog","elephant","lion"];
var listImg = ["cat","dog","elephant","lion"];
createListPanel();
function createListPanel()
{
var parent = $("#displayPanel").find("td").eq(0);
for(var i=0;i<list.length;i++)
{
parent.append("<div class='list' id="+i+">"+list[i]+"</div>");
}
$(".list").click(function(){
$("#detailDisplay").html(listImg[this.id]);
});
}
.list:hover{
background-color: #ffcccc;
}
.list{
background-color: #ffe6e6;
width:150px;
}
#displayPanel
{
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "displayPanel">
<table width="100%">
<tr><td ></td><td><div id="detailDisplay"></div></td></tr>
</table>
</div>
You can replace the text in the ListImg with your image url

Related

Add class if image has the class

I have some images which are way too big when I make the menu they're containing in smaller, that's why I made a second class where I changed the width and height.
I tried to add and remove the class with javascript like this:
if ($('img').hasClass('lorem')) {
$('img').removeClass('lorem')
$('img').addClass('smalllorem')
} else {
$('img').addClass('lorem')
$('img').removeClass('smalllorem')
}
Now this works perfectly fine, but this will add the classes to my other images on the website as well, how can I specify to only give the class "smalllorem" to the elements which have the class lorem? Because the other images don't have the class "lorem" they will still get the class "smalllorem" added on.
-> I don't get why images without the class "lorem" get into the code? I mean I ask if the image has class .. Why does it include the other image elements?
I would look for a CSS solution before moving on to a JavaScript one. But answering the question asked...
I don't get why images without the class "lorem" getting into the code ? I mean I ask if img has class
Because $("img") selects all images, but $("img").hasClass("lorem") only looks at the first image to see if it has the class. Then in each branch of your if/else, you're applying changes to all images ($("img").addClass("lorem");). jQuery's API is asymmetric in this regard: methods that tell you something about the element only look at the first element in the jQuery collection, but methods that change something apply to all elements in the collection.
If I understand you correctly, you want to:
Remove lorem from images that have it, adding smalllorem instead
and
Remove smalllorem from images that have it, adding lorem instead
Basically, you want to toggle both classes. There's a toggleClass method for that.
$("img.lorem, img.smalllorem").toggleClass("lorem smalllorem");
That selects all img elements that have either class, and toggles the classes on them.
Live Example:
setTimeout(() => {
$("img.lorem, img.smalllorem").toggleClass("lorem smalllorem");
}, 800);
.lorem {
border: 2px solid black;
}
.smalllorem {
border: 2px solid yellow;
}
<div>lorem (black border) => smalllorem (yellow border):</div>
<img class="lorem" src="https://via.placeholder.com/50.png/09f/fff">
<img class="lorem" src="https://via.placeholder.com/50.png/09f/fff">
<img class="lorem" src="https://via.placeholder.com/50.png/09f/fff">
<div>smalllorem (yellow border) => lorem (black border):</div>
<img class="smalllorem" src="https://via.placeholder.com/50.png/09f/fff">
<img class="smalllorem" src="https://via.placeholder.com/50.png/09f/fff">
<img class="smalllorem" src="https://via.placeholder.com/50.png/09f/fff">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Instead of adding a new class to the image you could just make it responsive :
.img {
width: 100%; //define width
max-width: 250px; //restrict the size (can use min-width aswell)
height: auto; //auto adjust depending on the width
}
var count = 0;
function resize(){
var menue = document.getElementById("container");
count++;
if(count % 2)
{
menue.style.width = "50%";
menue.style.height = "50px";
}
else
{
menue.style.width = "100%";
menue.style.height = "100px";
}
}
#container{
border: 1px solid black;
width: 100%;
height: 100px;
transition: 330ms;
}
#home{
width: 15%;
height: auto;
min-width:10px;
}
menue
<div id="container">
<img src="https://cdn-icons-png.flaticon.com/512/25/25694.png" id="home">
</div>
<br>
<input type="button" value="resize menue" onclick="resize()">

Reset Border style

I have a image that is currently being styled with Jquery once it's clicked. I eventually hide it in Javascript. I want to reshow it, but I want it to have the border removed.
Here is HTML:
<div id="playOptionsWager" style="display: none">
<h4>Choose your move to beat the computer!</h4>
<img id="clickedRockWager" src="img/rock.jpg" onclick="playWagerRock()" />
<img id="clickedPaperWager" src="img/paper.jpg" onclick="playWagerPaper()"/>
<img id="clickedScissorsWager" src="img/scissors.jpg" onclick="playWagerScissors()" />
</div>
Jquery:
$(function () {
$("img").on("click",function() {
$(this).siblings().css('border','0px')
$(this).css('border', "solid 2px red");
});
});
Here is what I was trying in Javascript:
function autobet() {
coinBalance -= currentBet*2;
alert(getBalance());
document.getElementsByTagName("IMG").style.border="";
}
However when it reshows the div it has the border on it still.
Thanks for the help!
Your issue is that document.getElementsByTagName("IMG") returns a collection of elements, so simply applying .style.border on this collection won't work. Instead, you need to loop over this collection, and set every image within it to have no border using .style.border = 0;:
See working example (with div) below:
function removeBorder() {
[...document.getElementsByTagName("div")].forEach(elem => {
elem.style.border = 0;
});
}
.box {
height: 100px;
width: 100px;
background: black;
display: inline-block;
}
.active {
border: 3px solid red;
}
<div class="box"></div>
<div class="box active"></div>
<div class="box"></div>
<br />
<button onclick="removeBorder()">Remove border</button>
Also note that [...document.getElementsByTagName("IMG")] is a way of converting the collection of elements into an array of elements, which thus allows us to use the .forEach method to loop over it.
You started with jQuery, let's continue with jQuery.
function autobet() {
coinBalance -= currentBet*2;
alert(getBalance());
$("img").css("border","");
}
The problem is that getElementsByTagName() returns a collection not one element.
First you need to iterate over the collection of html elements you have - when using getElementsByTagName you get back an array of elements.
Second you need to give the elements a style of zero.
const divElements = document.getElementsByTagName("IMG");
for (let i=0; i < divElements.length; i++) {
divElements[i].style.border = 0;
}
You can see the code on stackbliz -
https://stackblitz.com/edit/border-issue?file=index.js

Can't hide other elements while clicking on another

I'm trying to make a toggle which works, but every element I click on creates a stack of these showed elements. Instead I'm trying to hide everything and display only element that I clicked on. Now I can only hide it when I click on the same element twice, which is not what I want. I want to click on one and hide previous ones that were showing.
.totalpoll-choice-image-2 is a bunch of images that always has to be shown. They are what the user clicks on to display hidden description under each image. That description shows up when I click on .totalpoll-choice-image-2. There are 5 images with that class. The next image I click on, I want to hide the previous description box.
My code:
jQuery(document).ready(function() {
var element = document.getElementsByClassName("totalpoll-choice-image-2");
var elements = Array.prototype.slice.call(Array.from( element ) );
console.log(elements);
jQuery(element).each(function(item) {
jQuery(this).unbind('click').click(function(e) {
e.stopPropagation();
var id = jQuery(this).attr("data-id");
console.log(this);
//jQuery("#" + id).css({"display": 'block !important'});
//document.getElementById(id).style.setProperty( 'display', 'block', 'important' );
var descriptionContainer = document.getElementById(id);
var thiss = jQuery(this);
console.log(thiss);
console.log(jQuery(descriptionContainer).not(thiss).hide());
jQuery(descriptionContainer).toggleClass("show");
});
})
})
You can attach event handlers to a group of DOM elements at once with jQuery. So in this case, mixing vanilla JS with jQuery isn't doing you any favors - though it is possible.
I threw together this little example of what it sounds like you're going for.
The script itself is very simple (shown below). The classes and IDs are different, but the idea should be the same:
// Assign click handlers to all items at once
$('.img').click(function(e){
// Turn off all the texts
$('.stuff').hide();
// Show the one you want
$('#' + $(e.target).data('id')).show();
})
https://codepen.io/meltingchocolate/pen/NyzKMp
You may also note that I extracted the ID from the data-id attribute using the .data() method, and attached the event listener with the .click() method. This is the typical way to apply event handlers across a group of jQuery objects.
From what I understood based on your comments you want to show only description of image that has been clicked.
Here is my solution
$('.container').on('click', 'img', function() {
$(this).closest('.container').find('.image-description').addClass('hidden');
$(this).siblings('p').removeClass('hidden');
});
https://jsfiddle.net/rtsj6r41/
Also please mind your jquery version, because unbind() is deprecated since 3.0
You can use event delegation so that you only add your event handler once to the parent of your images. This is usually the best method for keeping work the browser has to do down. Adding and removing classes is a clean method for show and hide, because you can see what is happening by looking at your html along with other benefits like being easily able to check if an item is visible with .hasClass().
jsfiddle: https://jsfiddle.net/0yL5zuab/17/
EXAMPLE HTML
< div class="main" >
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="clear">
</div>
</div>
EXAMPLE CSS
.image-parent{
height: 100px;
width: 200px;
float: left;
margin: 5px;
}
.image-parent .image{
background: blue;
height: 50%;
width: 100%;
}
.image-descr{
display: none;
height: 50%;
width: 100%;
}
.show-descr{
display: block;
}
.clear{
clear: both;
}
EXAMPLE JQUERY
$(".main").on("click", ".image-parent", ShowDescription);
function ShowDescription(e) {
var $parent = $(e.target).parent(".image-parent");
var $desc = $parent.find(".image-descr");
$(".image-descr").removeClass("show-descr");
$desc.addClass("show-descr");
}

Gallery. Display divs corresponding to clicked <li> item. Javascript

I'm trying to build a basic gallery which displays a large image [div] depending on which image is clicked. The thumbnail images are stored in a basic unordered list.
I'm a javascript noob, I could use getElementById to change display class etc but I'd prefer not to have a separate function for each image, of which they're may be 100 or so.
Is there a way to call the same function to display a different div depending on which image is clicked [a larger version of that image]?
So:
If img1 is clicked display divA,
If img2 is clicked display divB,
If img3 is clicked display divC...
Many thanks.
The event passed to the onclick method has a target parameter, which refers to the element that was clicked.
Please post your code, preferably in a working JsFiddle, to get a more targeted answer.
Here is a general example of what you want to achieve:
document.onclick = function(e) {
// e.target is the img that was clicked, display the corresponding div
// Get the image number from the id
var number = e.target.id.substr(3)
// Display the corresponding div
document.getElementById('div' + number).style.visibility = 'visible';
}
Please note that the last line will most likely be different in your implementation - I don't know how you are displaying these divs.
You could try as follows
Assign id to all images in such a manner when they will be clicked we
could generate the corresponding div's id with some logical
manipulation.
Such as
images would have id like img_divA,img_divB and when they will be clicked , get there id and do some stuff like substring and you will get divA , divB and so on .. Finally show that by javascript ..
You could do something like this. Here actually a function is created per clickable dom element, but they are programmatically created. I use the num attribute to make the correspondence between the images to show and the images to click but there is many other (good) ways to do it.
// retrieve the divs to be clicked
var toClicks = document.querySelectorAll(".img-to-click");
[].forEach.call(toClicks, function(node){
// retrieve the target image
var num = node.getAttribute("num");
var target = document.querySelector(".img-to-show[num=\"" + num + "\"]");
// create the click listener on this particular dom element
// (one of the image to click)
node.addEventListener('click', function(){
// hide any currently displayed image
var current = document.querySelector(".img-to-show.shown");
if(current) current.classList.remove("shown");
// set the new current
target.classList.add("shown");
});
});
#to-display {
position: relative;
width: 100%;
height: 50px;
}
#to-click {
position: relative;
margin-top: 20px;
}
.img-to-show {
position: absolute;
width: 100%;
height: 100%;
display: none;
}
.img-to-show.shown {
display: block;
}
.img-to-click{
display: inline-block;
background-color: gray;
width: 50px;
color:white;
text-align: center;
line-height: 50px;
vertical-align: middle;
height: 50px;
cursor:pointer;
}
<div id="to-display">
<div class="img-to-show" num="1" style="background-color:blue;"></div>
<div class="img-to-show" num="2" style="background-color:red;"></div>
</div>
<div id="to-click">
<div class="img-to-click" num="1">1</div>
<div class="img-to-click" num="2">2</div>
</div>

Change CSS value by javascript for whole document

I want on ajax call change the values loaded from CSS file, it means not only for one element like:
document.getElementById("something").style.backgroundColor="<?php echo "red"; ?>";
but similar script which is change the css value generally, not only for element by ID, idealy like background color for CSS CLASS divforchangecolor:
CSS:
.divforchangecolor{
display: block;
margin: 20px 0px 0px 0px;
padding: 0px;
background-color: blue;
}
HTML:
<div class="divforchangecolor"><ul><li>something i want to style</li><ul></div>
<div class="divforchangecolor">not important</div>
<div class="divforchangecolor"><ul><li>something i want to style</li><ul></div>
<div class="divforchangecolor">not improtant</div>
Ideal solution for me:
onclick="--change CSS value divforchangecolor.backgroundColor=red--"
but i need to change CSS to reach .divforchangecolor ul li and .divforchangecolor ul li:hover
If you can't just apply the classname to these elements. You could add a new selector to your page. The following vanilla JS would be able to do that (jsFiddle).
function applyDynamicStyle(css) {
var styleTag = document.createElement('style');
var dynamicStyleCss = document.createTextNode(css);
styleTag.appendChild(dynamicStyleCss);
var header = document.getElementsByTagName('head')[0];
header.appendChild(styleTag);
};
applyDynamicStyle('.divforchangecolor { color: pink; }');
Just adapt the thought behind this and make it bullet proof.
var elements=document.getElementsByClassName("divforchangecolor");
for(var i=0;i<elements.length;i++){
elements[i].style.backgroundColor="red";
}
var e = document.getElementsByClassName('divforchangecolor');
for (var i = 0; i < e.length; i++) e[i].style.backgroundColor = 'red';
Use getElementByClassName() and iterate over the array returned to achieve this
You can select elements by class with document.getElementsByClassName or by css selector (includes class) with document.querySelectorAll().
Here are two approaches, for example: Live demo here (click).
Markup:
<div class="divforchangecolor"></div>
<div class="divforchangecolor"></div>
<div class="divforchangecolor"></div>
<div class="divforchangecolor"></div>
<div class="some-container">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
JavaScript:
var toChange = document.getElementsByClassName('divforchangecolor');
for (var i=0; i<toChange.length; ++i) {
toChange[i].style.backgroundColor = 'green';
}
var toChange2 = document.querySelectorAll('.some-container > div');
for (var i=0; i<toChange.length; ++i) {
toChange2[i].style.backgroundColor = 'red';
}
I recommend the second solution if it is possible in your case, as the markup is much cleaner. You don't need to specifically wrap the elements in a parent - elements already have a parent (the body, for example).
Another option is to have the background color you want to change to in a css class, then you can change the class on your elements (and therefore the style changes), rather than changing the css directly. That is also good practice, as it lets you keep your styles all in css files, while js is just manipulating which one is used.
On the whole document your approach can be a bit different:
ajax call
call a function when done
conditionally set a class on the body like <body class='mycondition'></body>
CSS will take care of the rest .mycondition .someclass: color: red;
This approach will be more performant than using JavaScript to change CSS on a bunch of elements.
You can leverage CSS selectors for that:
.forchangecolor {
display: block;
margin: 20px 0px 0px 0px;
padding: 0px;
background-color: blue;
}
.red-divs .forchangecolor {
background-color: red;
}
Then, with javascript, add the red-divs class to a parent element (could be the <body>, for example), when one of the divs is clicked:
document.addEventListener("click", function(event) {
var target = event.target;
var isDiv = target.className.indexOf("forchangecolor") >= 0;
if(isDiv) {
document.body.classList.add("red-divs");
}
});
Working example: http://jsbin.com/oMIjASI/1/edit

Categories