I have setup a click event in Javascript which is not working for some reason, the image just isn't changing and there are no errors in the console. The image src is meant to change when clicking the html icon.
Here is the javascript:
document.querySelector(".left").addEventListener("click", () => {
leftArrow();
});
Here is the leftArrow function:
leftArrow: () => {
if (document.querySelector(DOMStrings.characterImg).src === characters[0]) {
document.querySelector(DOMStrings.characterImg).classList.add("boris");
document.querySelector(DOMStrings.characterImg).src = characters[1];
const el = document.querySelector(DOMStrings.characterImg);
console.log(el);
} else if (document.querySelector(DOMStrings.characterImg).src === characters[1]) {
document.querySelector(DOMStrings.characterImg).classList.remove("boris");
document.querySelector(DOMStrings.characterImg).src = characters[0];
const el = document.querySelector(DOMStrings.characterImg);
console.log(el);
}
Here is where the images are stored:
const characters = ["Resources/Images/trump.png", "Resources/Images/boris.png"];
Here is where the DOM strings are stored:
const DOMstrings = {
characterImg: ".character-img"
}
Lastly, here is the relevant html:
<div class="character-select">
<ion-icon class="left" name="arrow-dropleft-circle"></ion-icon>
<ion-icon class="right" name="arrow-dropright-circle"></ion-icon>
<img class="character-img" src="Resources/Images/trump.png">
</div>
//below HTML part
/*
<div class="character-select">
<ion-icon class="icon" id='left' name="arrow-dropleft-circle"></ion-icon>
<ion-icon class="icon" id='right' name="arrow-dropright-circle"></ion-icon>
<img class="character-img" src="Resources/Images/trump.png">
</div>
*/
-----------------------------------------------------------------------
//javascript part
document.querySelectorAll(".icon").forEach(function(item,index){
item.addEventListener('click',function(event){
if(event.targer.id='right'){
document.querySelector('.character-img').src='your source that you want to set'
}else if(event.targer.id='left'){
document.querySelector('.character-img').src='your source that you want to set'
}
});
});
Related
I'm trying to update the HTML when a button is clicked.
I have tried to solve this issue for a few hours now and I don't know if I'm stupid, but the images are not changing.
const slider = document.querySelector(".slider")
const btn = document.querySelector(".next")
const btn2 = document.querySelector(".previous")
const images = ['car.jpg', `left.jpg`]
window.addEventListener("load", iniliatizeSlider())
function iniliatizeSlider(){
var x = 0
cars = ''
cars += `<div class="slide">
<img src="${images[x]}" alt"client">
<br><br>
</div>`
slider.innerHTML = cars;
}
btn.addEventListener("click", consoleMsg)
btn2.addEventListener("click", consoleMsg2)
function consoleMsg(){
x=1
}
function consoleMsg2(){
x=0
}
<section id="slider-section">
<div class="container">
<div class="subcontainer">
<div class="slider-wrapper">
<h2>client showcase</h2>
<br />
<div class="slider"></div>
<div id="controls">
<button class="previous">
<img src="left.jpg" alt="previous client" />
</button>
<button class="next">
<img src="right.jpg" alt="next client" />
</button>
</div>
</div>
</div>
</div>
</section>
I was expecting the image to change when the button was clicked, but the image stayed the same, but the value of x changed.
Your initialize function is running once, when the page loads and at that point you are setting the image source to 0 and you never change it after that. You need to adjust the image source within the functions that react to button clicks. Now you do update x in those functions but nothing is ever done with x after that point.
A couple of other things... With .addEventListener(), you pass a reference to the callback function, not invoke the function, so the line should be: window.addEventListener("load", iniliatizeSlider) <-- no () after the function name.
Also, you don't need to replace the HTML on the page to update the image, you only need to update the image's src property.
See comments below:
// Get a reference to an existing image element.
// No need to recreate the <img> element.
const img = document.querySelector(".slider img");
const next = document.querySelector(".next");
const prev = document.querySelector(".previous");
const images = ["https://cache.mrporter.com/content/images/cms/ycm/resource/blob/1252204/68e7f03297f41cb3ce41f15ec478f70f/image-data.jpg/w1500_q80.jpg", "https://play-lh.googleusercontent.com/VC7rta8PIK3MqmQG5c-F5CNJQ6cCv6Eb-kyBoUcQ2xj83dZVhn7YCj_GIWW8y7TnAMjU=w240-h480-rw"];
let currentIndex = 0; // Keeps track of which image is shown
next.addEventListener("click", function(){
// Check to see if we're at the end of the array
if(currentIndex === images.length-1){
currentIndex = 0; // Reset index
} else {
currentIndex++; // increase the index
}
img.src = images[currentIndex]; // Just update the existing image's source
});
prev.addEventListener("click", function(){
// Check to see if we're at the beginning of the array
if(currentIndex === 0){
currentIndex = images.length-1; // Reset index
} else {
currentIndex--; // decrease the index
}
img.src = images[currentIndex]; // Just update the existing image's source
});
img { width:50px; }
<section id="slider-section">
<div class="container">
<div class="subcontainer">
<div class="slider-wrapper">
<h2>client showcase</h2>
<br >
<div class="slider">
<!-- Here, we just put a static image element with the first image we want to see. -->
<img src="https://cache.mrporter.com/content/images/cms/ycm/resource/blob/1252204/68e7f03297f41cb3ce41f15ec478f70f/image-data.jpg/w1500_q80.jpg">
</div>
<div id="controls">
<button class="previous">
<img src="left.jpg" alt="previous client">
</button>
<button class="next">
<img src="right.jpg" alt="next client">
</button>
</div>
</div>
</div>
</div>
</section>
Call the function initializeSlider() on click of btn instead of consoleMsg().
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>
I am new to Javascript and I try to add an event listener for each button on every card, but the code make the last card (button) only have the event 'click' so is there's any way to make it happen with innerHTML card
this is the code:
let tracksRender = (track) => {
track.forEach(element => {
//this the card that will add the button for
let card = `<div class="card">
<div class="image">
<img class="image_img" src="${element.artwork_url || 'http://lorempixel.com/100/100/abstract/'}">
</div >
<div class="content">
<div class="header">
${element.title}
</div>
</div>
</div >`;
//here i add the card to DOM
let searchResults = document.querySelector('.js-search-results');
searchResults.innerHTML += card;
// store the content of the button
let inBtn = `<i class="add icon"></i>
<span>Add to playlist</span>`;
// created button container
let btn = document.createElement("div");
btn.classList.add("ui", "bottom", "attached", "button", "js-button");
// added the content of the button
btn.innerHTML += inBtn;
// here i add the the event Listener to the button
btn.addEventListener('click', () => {
console.log("click");
});
//here i add the button to the last card have been created
searchResults.querySelector(".card:last-child").append(btn);
});
}
and the structure:
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>SoundCloud Player</title>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css'>
<link rel='stylesheet' href='styles/main.css'>
<style></style>
</head>
<body id="soundcloud-player">
<div class="ui container col">
<div class="col">
<div class="main">
<div class="js-search-results search-results ui cards">
</div>
</div>
</div>
</div>
<script src="https://connect.soundcloud.com/sdk/sdk-3.3.2.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js'></script>
<script src="javascript/main.js"></script>
</body>
</html>
Fiddle: https://jsfiddle.net/y73bstju/7/
but it will add the event to the last card only
It might help to create elements instead of appending innerHTML:
let tracksRender = (track) => {
// Select the results here, so you wont have to repeat it
const searchResults = document.querySelector('.js-search-results');
track.forEach(element => {
// Create the card, give it its class and innerHTML
const card = document.createElement('div');
card.className = 'card';
card.innerHTML = `<div class="image">
<img class="image_img" src="${element.artwork_url || 'http://lorempixel.com/100/100/abstract/'}">
</div >
<div class="content">
<div class="header">
${element.title}
</div>
</div>`;
// Created the button, give its classes and innerHTML
const btn = document.createElement('div');
btn.className = 'ui bottom attached button js-button';
btn.innerHTML = '<i class="add icon"></i><span>Add to playlist</span>';
// Add the event listener
btn.addEventListener('click', () => {
console.log('click');
});
// Append the button to the created card
card.appendChild(btn);
// Add the card to the results
searchResults.appendChild(card);
});
}
I agree with you that theoretically the object should have the event, but the behavior we experience is that whenever another write happens at the relevant section of the DOM, the event handler is lost, which is the reason the last element has the click event. So, let's write first into the DOM and only when we are done with that should we add the event listeners, like:
let SoundCloudAPI = {};
SoundCloudAPI.init = () => {
SC.initialize({ client_id: 'cd9be64eeb32d1741c17cb39e41d254d' });
};
SoundCloudAPI.init();
SoundCloudAPI.getTrack = (inputVlue) => {
SC.get('/tracks', {
q: inputVlue
}).then((tracks) => {
console.log(tracks);
SoundCloudAPI.renderTracks(tracks);
});
}
SoundCloudAPI.getTrack("alan walker");
SoundCloudAPI.renderTracks = (track) => {
track.forEach(element => {
//this the card that will add the button for
let card = `<div class="card">
<div class="image">
<img class="image_img" src="${element.artwork_url || 'http://lorempixel.com/100/100/abstract/'}">
</div >
<div class="content">
<div class="header">
${element.title}
</div>
</div>
</div >`;
//here i add the card to DOM
let searchResults = document.querySelector('.js-search-results');
searchResults.innerHTML += card;
// store the content of the button
let inBtn = `<i class="add icon"></i>
<span>Add to playlist</span>`;
// created button container
let btn = document.createElement("div");
btn.classList.add("ui", "bottom", "attached", "button", "js-button", "fresh");
// added the content of the button
btn.innerHTML += inBtn;
//here i add the button to the last card have been created
searchResults.querySelector(".card:last-child").append(btn);
});
for (let btn of document.querySelectorAll('.ui.attached.button.js-button.fresh')) {
// here i add the the event Listener to the button
btn.addEventListener('click', () => {
console.log("click");
});
}
}
Fiddle: https://jsfiddle.net/r84um9pt/
I think:
you're doing:
let searchResults = document.querySelector('.js-search-results');
searchResults.innerHTML += card;
Serializing again and again in your div "searchResults"
innerHTML ~erases~ listeners, and probably it is ~erasing~ your previous listeners. Besides, i don't remember where i read that innerHTML script code cannot run (for security purposes)
From https://medium.com/#kevinchi118/innerhtml-vs-createelement-appendchild-3da39275a694
using innerHTML reparses and recreates all DOM nodes inside the div
element and is less efficient than simply appending a new element to
the div. In the above cases, createElement is the more performant
choice.
Be careful:
Using "append" again and again uses badly browser resources, redrawing many times.
But, you can append in a documentFragment and append it to the div -js-search-results
DocumentFragment:
https://developer.mozilla.org/es/docs/Web/API/DocumentFragment
Welcome in the community. In you're code you're adding many classes to button. You can add event Listener to any one of the unique class name which is specifically applied on button element only.
You can replace:
btn.addEventListener('click', () => {
console.log('click');
});
with:
document.querySelectorAll('.js-button').forEach(el=>{
el.addEventListener('click', (event) => {
event.preventDefault();
console.log("click");
});
});
Also, it would be good if you add eventListener out of the loop in which you are appending elements.
How do I loop through all the images using the call trigger, when I click on the image a modal popup should show my text and image.
var modal = document.querySelector(".modal");
var trigger = document.querySelector(".trigger");
var closeButton = document.querySelector(".close-button");
function toggleModal() {
modal.classList.toggle("show-modal");
}
function windowOnClick(event) {
if (event.target === modal) {
toggleModal();
}
}
trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
}
<div portfolio-item ">
<a class="trigger "><img src="images/techify.jpg "/></a>
<div class="modal ">
<div class="modal-content ">
<img class="modalimages " src ="Images/techify.jpg ">
<div class="modal-text ">
<p> It is all about a training institute</p>
</div>
</div>
</div>
</div>
<div class="modal-content ">
<img class="modalimages " src ="Images/HairStyling.jpg ">
</div>
</div>
Going by what you've supplied there are a few minor issues that would even prevent this from running, so I had to make some small changes to the code before I could even begin. One being the } placed at the end of your script.
Another being the <div portfolio-item"> only having one ".
This may or may not be what you're trying to accomplish, but we'd need more information in order to know.
<style>
.modal { display: block; }
.show-modal { display: none; }
</style>
<div portfolio-item>
<a class="trigger">
<img src="images/techify.jpg"/>
</a>
<div class="modal">
<div class="modal-content">
<img class="modalimages" src="Images/techify.jpg">
<div class="modal-text">
<p> It is all about a training institute</p>
</div>
</div>
</div>
<div class="modal-content">
<img class="modalimages" src="Images/HairStyling.jpg">
</div>
</div>
<button class="close-button">Close Button</button>
<script>
var modal = document.querySelectorAll(".modal");
var trigger = document.querySelector(".trigger");
var closeButton = document.querySelector(".close-button");
function toggleModal() {
for(i=0;i<modal.length;i++){
modal[i].classList.toggle("show-modal");
}
}
function windowOnClick(event) {
if (event.target === modal) {
toggleModal();
}
}
trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
</script>
If you've looking for both images to be hidden on the first image click or by pressing the button (which I also had to add) you'll need to move the following code up by one line
<div class="modal-content">
<img class="modalimages" src="Images/HairStyling.jpg">
</div>
If you want to add an event to every image, you could use some Javascript like this:
var images = document.querySelectorAll("img")
for( var i = 0 ; i < images.length ; i++ ) {
images[i].addEventListener("click" someFunction)
}
This make it so that when any image is clicked, it calls the someFunction function
I can't adjust my text to be center aligned. I tried to put css code in onmouseover="hover('')" but it doesn't work. What is the get around for this?
Middle circle with id="content" that changes the tag on hover
<div id="circle">
<p id="content">
<b><span>Services</span></b>
</p>
</div>
JS Code that I included in the html tag to change content on hover
<a href="">
<div onmouseover="hover('<b>BPO</b>')" onmouseout="hover('<b>Services</b>')" class="scaling" id="circle-2">
<img src="/static/img/2.png" onmouseover="this.src='/static/img/2b.png'" onmouseout="this.src='/static/img/2.png'" style="margin-top:5px;" width=100px/>
</div>
</a>
<a href="">
<div onmouseover="hover('<b>Web Development</b>')" onmouseout="hover('<b>Services</b>')" class="scaling" id="circle-3">
<img src="/static/img/4.png" onmouseover="this.src='/static/img/4b.png'" onmouseout="this.src='/static/img/4.png'" style="margin-top:5px;" width=100px/>
</div>
</a>
JS Code that changes the content of the <p> tag
function hover(description) {
console.log(description);
document.getElementById('content').innerHTML = description;
}
everything is working properly but I can't adjust the text to be in the center regard less of the <p> tag length .
The main question is how do i add css code in onmouseover="hover('')"
What i want it to look like
what it looks like
Your code really needed a lot of cleaning up.
You should separate the HTML, CSS and JavaScript. After doing this, debugging is SO much easier and the code is much simpler to follow.
In addition, you had a great deal of duplication in your code. Again, using CSS and JavaScript can remove that redundancy. For example, styling is done with CSS, not HTML. Tags like <b> are deprecated and should no longer be used. By creating CSS styles that incorporate font-weight:bold and applying those styles properly, we can get rid of all the <b> and </b> tags.
// Get all DOM references:
var content = document.getElementById('content');
var cir2 = document.getElementById("circle-2");
var cir3 = document.getElementById("circle-3");
var img1 = document.getElementById("img1");
var img2 = document.getElementById("img2");
// Attach event handlers:
cir2.addEventListener("mouseover", function(){ hover('BPO') });
cir2.addEventListener("mouseout", function(){ hover('Services') });
cir3.addEventListener("mouseover", function(){ hover('Web Development') });
cir3.addEventListener("mouseout", function(){ hover('Services') });
img1.addEventListener("mouseover", function(e){ changeSource(e,'http://plumseattle.com/wp-content/uploads/2016/01/linkedin-logo.jpg') });
img1.addEventListener("mouseout", function(e){ changeSource(e, 'https://cdn3.iconfinder.com/data/icons/free-social-icons/67/facebook_circle_color-256.png') });
img2.addEventListener("mouseover", function(e){ changeSource(e, 'http://seeklogo.com/images/S/snapchat-logo-2D9C3E7ADA-seeklogo.com.png') });
img2.addEventListener("mouseout", function(e){ changeSource(e, 'https://www.seeklogo.net/wp-content/uploads/2011/06/Twitter-icon-vector-400x400.png') });
function hover(description) {
//console.log(description);
content.textContent = description;
}
function changeSource(evt, source){
evt.target.src = source;
}
content > span { font-weight: bold;}
.scaling { font-weight:bold; }
.img { margin-top:5px;width:100px; }
<div id="circle">
<p id="content">
<span>Services</span>
</p>
</div>
<a href="">
<div class="scaling" id="circle-2">
<img id="img1"
src="https://cdn3.iconfinder.com/data/icons/free-social-icons/67/facebook_circle_color-256.png"
class="img">
</div>
</a>
<a href="">
<div class="scaling" id="circle-3">
<img id="img2"
src="https://www.seeklogo.net/wp-content/uploads/2011/06/Twitter-icon-vector-400x400.png"
class="img">
</div>
</a>
Typically, if you want some element to listen to "mouseover" event, the best way to go is to use EventTarget#addEventListener. Just like this:
const node = document.getElementById('hover');
node.addEventListener('mouseover', () => {
node.innerText = `Last time mouseover'd at ${new Date()}.`;
});
So, now, you need to update children of #content and src attribute of an image under mouse cursor.
The HTML would look like this:
<p id="content">
Services
</p>
<a href="">
<div class="scaling" id="circle-2">
<img src="/static/img/2.png" />
</div>
</a>
<a href="">
<div class="scaling" id="circle-3">
<img src="/static/img/2.png" />
</div>
</a>
while JS code would look like this:
const content = document.getElementById('content');
const circle2 = document.getElementById('circle-2');
const circle3 = document.getElementById('circle-3');
circle2.addEventListener('mouseover', () => {
circle2.children[0].src = '/static/img/2b.png';
content.innerText = 'BPO';
});
circle2.addEventListener('mouseout', () => {
circle2.children[0].src = '/static/img/2.png';
content.innerText = 'Services';
});
circle3.addEventListener('mouseover', () => {
circle3.children[0].src = '/static/img/4b.png'
content.innerText = 'Web Development';
});
circle3.addEventListener('mouseout', () => {
circle3.children[0].src = '/static/img/4.png'
content.innerText = 'Services';
});
(check out this fiddle).