Jquery click multiple IDs and get value - javascript

I'm trying to get the value of an element when a user click on it. This is my code:
<div id="heroes-selection" class="row dflex justify-content-left">
<figure id="luna" class="heroes-pic border text-danger m-3" value="heroes.luna">
<img class="animated-gif">
</figure>
<figure id="qop" class="heroes-pic border text-danger m-3" value="heroes.qop">
<img class="animated-gif">
</figure>
</div>
I've tried to use Jquery $(this) and the result came out as undefined.
$(".heroes-pic").on("click", () => {
player = $(this).attr("value");
console.log(player);
});
My goal is to get the value heroes.luna when the user click on the figure with id="luna". The same for id="qop", I need to get the value heroes.qop. Thank you!

You have to use the classic function instead of arrow function. this on arrow function refers to the HTMLDocument and on the object clicked. And that is the reason why you are not getting the correct result. You are getting attr value from HTMLDocument.
$(".heroes-pic").on("click", function() {
player = $(this).attr("value");
console.log(player);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="heroes-selection" class="row dflex justify-content-left">
<figure id="luna" class="heroes-pic border text-danger m-3" value="heroes.luna"> heroes.luna
<img class="animated-gif">
</figure>
<figure id="qop" class="heroes-pic border text-danger m-3" value="heroes.qop"> heroes.qop
<img class="animated-gif">
</figure>
</div>
Other option: you can use event.currentTarget instead of this on arrow function
Like:
$(".heroes-pic").on("click", (event) => {
player = $(event.currentTarget).attr("value");
console.log(player);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="heroes-selection" class="row dflex justify-content-left">
<figure id="luna" class="heroes-pic border text-danger m-3" value="heroes.luna">
<img class="animated-gif">heroes.luna
</figure>
<figure id="qop" class="heroes-pic border text-danger m-3" value="heroes.qop">
<img class="animated-gif">heroes.qop
</figure>
</div>

This is because you are using an arrow function that binds the this parameter to the enclosing scope's this.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this
replace it with a function:
$(".heroes-pic").on("click", function () {
player = $(this).attr("value");
console.log(player);
}

Related

How to get specific Div's/Card Details when user clicked that using javascript

I am creating various cards using fetch API, this cards are holding details like (Author, Title, Cover Image, etc.).
There is a lot of cards renders there once API call my struggle is how to get specific card data/details like ( author, title etc.) of clicked card. when user clicked any of the card from these set.
HTML
<div class="row" id="ShowReports">
<div class="col-lg-3 col-md-4 col-sm-6 mt-3" onclick="show(this)" id="card">
<div class="card p-1">
<img src="https://d3i5mgdwi2ze58.cloudfront.net/znuxxu2npw851eeboqayu3e35udn" alt="image"
class="bookimg" width="150" height="200">
<h6 class="mb-3 booktitle">${title1}</h6>
<p class="mb-0 bookpara" name="author">Author : ${author1}</p>
<p class="mb-3 bookpara" name="pages">Pages : ${pages1}</p>
Download1
</div>
</div>
<div class="col-lg-3 col-md-4 col-sm-6 mt-3" onclick="show(this)" id="card">
<div class="card p-1">
<img src="https://d3i5mgdwi2ze58.cloudfront.net/znuxxu2npw851eeboqayu3e35udn" alt="image"
class="bookimg" width="150" height="200">
<h6 class="mb-3 booktitle">${title2}</h6>
<p class="mb-0 bookpara" name="author">Author : ${author2}</p>
<p class="mb-3 bookpara" name="pages">Pages : ${pages2}</p>
Download2
</div>
</div>
</div>
javaScript
function show() {
var details = this.innerHTML
console.log(details)
}
Don't know what is the right approach or method to this...
UPDATED
We need to assign unique id to data elements. For example: id="${id}-author". Note that id is from your card id
<div class="col-lg-3 col-md-4 col-sm-6 mt-3" onclick="show(${id})" id="card">
<div class="card p-1">
<img src="https://d3i5mgdwi2ze58.cloudfront.net/znuxxu2npw851eeboqayu3e35udn" alt="image"
class="bookimg" width="150" height="200">
<h6 class="mb-3 booktitle" id="${id}-booktitle">${title1}</h6>
<p class="mb-0 bookpara" name="author" id="${id}-author">Author : ${author1}</p>
<p class="mb-3 bookpara" name="pages" id="${id}-pages">Pages : ${pages1}</p>
Download1
</div>
</div>
After that, we can implement show function like below
function show(id) {
const author = document.getElementById(id + "-author").innerHTML;
const booktitle = document.getElementById(id + "-booktitle").innerHTML;
const pages = document.getElementById(id + "-pages").innerHTML;
console.log({ author, booktitle, pages })
}
If you don't want to modify HTML, you also can try this way
onclick="show({ author: ${author}, booktitle: ${booktitle}, pages: ${pages} })"
And you need to have params corresponding to your data name
function show({ author, booktitle, pages }) {
console.log({ author, booktitle, pages })
}
OLD ANSWER
onclick="show(this)"
this in this context is referred to the global one, but from my understanding of your question, you're trying to get scoped context, so the change could be
onclick="show(event)"
To access the innerHTML from that click, you can try this way
function show(event) { //the param needs to be passed properly
var currentElement = event.target || event.srcElement;
var details = currentElement.innerHTML
console.log(details)
}
P/s: If you want to keep the global context on this, you also need to pass the param on show function.
# Nick Vu thanks for your comment your approach is quite logical and great well what i have did is, I have assigned a unique id to every card div while calling API and then target its childnode's innerHTMLS.
HTML
<div class="col-lg-3 col-md-4 col-sm-6 mt-3" id="card">
<div class="card p-1" id="second" onclick="show(id)">
<img src="https://d3i5mgdwi2ze58.cloudfront.net/znuxxu2npw851eeboqayu3e35udn" alt="image"
class="bookimg" width="150" height="200">
<h6 class="mb-3 booktitle">${title2}</h6>
<p class="mb-0 bookpara" name="author">Author : ${author2}</p>
<p class="mb-3 bookpara" name="pages">Pages : ${pages2}</p>
Download2
</div>
</div>
</div>
javascript
function show(e) {
console.log(e)
var details = document.getElementById(e)
console.log(details)
console.log(details.childNodes[1].src)
console.log(details.childNodes[3].innerHTML)
console.log(details.childNodes[5].innerHTML)
console.log(details.childNodes[7].innerHTML)
}
this is working around what i want as output.. thanks. Or may be at last i can do forEach loop of childnodes to make it more short.

Getting element values in jquery

I spent lots of time trying to figure out getting a values from an element using jquery. Here's the code
<div class="school">
<div class="school-prev">
<img src="images/photos.png" class="img-responsive" alt="" />
</div>
<h5 class="school-title">Admin</h5>
<small class="text-muted">School Board</small>
</div>
<div class="school">
<div class="school-prev">
<img src="images/photos2.png" class="img-responsive" alt="" />
</div>
<h5 class="school-title">Finance</h5>
<small class="text-muted">School Board</small>
</div>
Jquery Coe
$(document).ready(function(){
$(".school").click('.school-title', function(e){
var showValue=$(this).text();
alert(showValue);
});
});
Example of return values: Admin School Board;
Expected value is should be "Admin or Finance"
NB: Any solution should consider outside div(school) clickable and not school-title div alone.
Warm regards.
Try the following jQuery code:
$(document).ready(function(){
// console.log('th');
$(document).on('click','.school .school-title', function(e){
e.preventDefault()
var th = $(this); //change over here
console.log(th.text());
});
});
You can change $(".school").click('.school-title', function(e){ to $(".school").on('click', '.school-title', function(e) { and it will solve the problem for you.
After updating your NB, you can use:
$(document).ready(function() {
$(".school").click(function(e) {
var showValue = $('.school-title',this).text()
alert(showValue);
});
});
Demo
$(document).ready(function() {
$(".school").click(function(e) {
var showValue = $('.school-title',this).text()
alert(showValue);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="school">
<div class="school-prev">
<img src="images/photos.png" class="img-responsive" alt="" />
</div>
<h5 class="school-title">Admin</h5>
<small class="text-muted">School Board</small>
</div>
<div class="school">
<div class="school-prev">
<img src="images/photos2.png" class="img-responsive" alt="" />
</div>
<h5 class="school-title">Finance</h5>
<small class="text-muted">School Board</small>
</div>
You want a click anywhere in the school div to get the title - not just on the title itself. To do that, you just need to check for the school-title child element in the click function on school.
This will get all children with the class school-title (of which there will only be one - it works the same as find except on direct children only) and get the text from it:
$(document).ready(function(){
$(".school").click('.school-title', function(e){
var showValue=$(this).children('.school-title').text();
alert(showValue);
});
});
/* Just for illustration to make it easier to see what is happening */
.school { border: 1px solid #ccc;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="school">
<div class="school-prev">
<img src="images/photos.png" class="img-responsive" alt="" />
</div>
<h5 class="school-title">Admin</h5>
<small class="text-muted">School Board</small>
</div>
<div class="school">
<div class="school-prev">
<img src="images/photos2.png" class="img-responsive" alt="" />
</div>
<h5 class="school-title">Finance</h5>
<small class="text-muted">School Board</small>
</div>
You only have one child with school-title in this case, but it will work with multiple titles if needed (e.g. if you did want to get "Admin School Board" for example, you could simply add the school-title class to the text-muted element).
Reference: jQuery children documentation
You are using 'school' class name for the click event and want to get the value child element of div. That is not possible in this way.
Simply Change the code "$(this).text();" to "$(classname,this).text();".
Happy coding.

Mouseover function not working for first time

With this function i want to replace a static image with an animated image (gif) on mouseover. But it's not working only on FIRST mouseover. Is there someone that could help me?
JQuery function:
function mouseListener(imageDiv, image, animated, static)
{
$(function() {
$(imageDiv).hover(
function() {
$(image).attr("src", animated);
},
function() {
$(image).attr("src", static);
}
);
});
}
HTML:
<div onmouseover="mouseListener('#would_youDiv','#would_you','images/would_you.gif','images/would_you.jpg');" id="would_youDiv" class="container">
<a href="work.html">
<img id="would_you" class="img-fluid" src="images/would_you.jpg" width="100%" height="100%" />
<div class="overlay">
<div class="text">WOULD YOU</div>
</div>
</a>
</div>
You could make this much easier by generalizing the logic with classes and data elements.
$(document).ready(function() {
$('.hover-image-container').hover(
function() {
//find the image in the container
var $img = $(this).find('img');
//set the src to the animaged src on it
$img.attr('src', $img.data('animated-src'));
},
function() {
//find the image in the container
var $img = $(this).find('img');
//set the src to the original src
$img.attr('src', $img.data('src'));
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container hover-image-container">
<a href="work.html">
<img src="images/would_you.jpg" data-src="images/would_you.jpg" data-animated-src="images/would_you.gif" width="100%" height="100%" />
<div class="overlay">
<div class="text">WOULD YOU</div>
</div>
</a>
</div>
Your mouseListener method is called when the mouseover event occurs, which is when it creates the listener to the event, instead of acting on the event. You don't need to add the listener, since you've already registered the function to be called on mouse over, you just need to do the action you want for that event.
You need to either put that binding somewhere else, or create two methods that are bound to onmouseover and onmouseout.
For example, if you want to go the two methods route (as that's most similar to your current code):
<div onmouseover="mouseOverListener('#would_youDiv','#would_you','images/would_you.gif','images/would_you.jpg');" onmouseout="mouseOutListener('#would_youDiv','#would_you','images/would_you.gif','images/would_you.jpg');" id="would_youDiv" class="container">
<a href="work.html">
<img id="would_you" class="img-fluid" src="images/would_you.jpg" width="100%" height="100%" />
<div class="overlay">
<div class="text">WOULD YOU</div>
</div>
</a>
</div>
And then in your Javascript:
function mouseOverListener(imageDiv, image, animated, static) {
$(image).attr("src", animated);
}
function mouseOutListener(imageDiv, image, animated, static) {
$(image).attr("src", static);
}
You don't need a js function
HTML
<div class="container">
<a href="work.html">
<img class="img-fluid" src="images/would_you.jpg" width="100%" height="100%" onmouseover="this.src='images/would_you.gif'" onmouseout="this.src='images/would_you.jpg'"/>
<div class="overlay">
<div class="text">WOULD YOU</div>
</div>
</a>
</div>

Add button to new element

Can you help me solve a little problem?
I have some set of figures. After click, selected figure copied to another div (basket).
In the basket should appear new button. But in my solution this buttom appeared again after each click.
How I can fix this?
Thanks and sorry for my English
This code
<div class="products__list__items">
<div class="products__list__item row">
<figure class="product first" data-class="first">
<img src="https://www.tineye.com/images/robot-search-header.png" alt="product1" class="product__img">
<figcaption class="product__title">One</figcaption>
</figure>
</div>
<div class="products__list__item row">
<figure class="product first" data-class="first">
<img src="https://www.tineye.com/images/robot-search-header.png" alt="product1" class="product__img">
<figcaption class="product__title">Two</figcaption>
</figure>
</div>
<div class="products__list__item row">
<figure class="product first" data-class="first">
<img src="https://www.tineye.com/images/robot-search-header.png" alt="product1" class="product__img">
<figcaption class="product__title">Three</figcaption>
</figure>
</div>
</div>
<div class="basket">
</div>
Jquery code
$(document).ready(function() {
var addToBasket = function() {
var that = $(this);
if(!that.hasClass('added')) {
that.clone().appendTo($('.basket'));
that.addClass('added');
};
$('.basket .product').append('<button>x</button>');
};
$(document).on("click",".products__list__item .product",addToBasket);
});
Here fiddle
https://jsfiddle.net/fhxx9hm3/
You should add the button only once per product.
var addToBasket = function() {
var that = $(this);
if(!that.hasClass('added')) {
//Append the button here
that.clone().add('<button>x</button>').appendTo($('.basket'));
//Or
//that.clone().append('<button>x</button>').appendTo($('.basket'));
that.addClass('added');
};
//Following statement is not required
//$('.basket .product').append('<button>x</button>');
};
DEMO

Javascript mouseover/mouseout animation working for first iteration only

I created a javascript animation to move a picture to the right when on mouseover and to go back to its resting position when the mouse exits the image. It works flawlessly for the first image but when I try the other iterations the first image moves instead of the one I hover on.
Here is the HTML code:
<div class="sectionJoueur">
<div class="scroller">
<figure id="infos" class="nomPositionCourt A">
<img src="images/infoMathieuD.png">
</figure>
<figure class="img">
<img src="images/md.jpg">
</figure>
</div>
</div>
<div class="sectionJoueur">
<div class="scroller">
<figure id="infos" class="nomPositionCourt B">
<img src="images/infoMathieuD.png">
</figure>
<figure class="img">
<img src="images/md.jpg">
</figure>
</div>
</div>
<div class="sectionJoueur">
<div class="scroller">
<figure id="infos" class="nomPositionCourt C">
<img src="images/infoMathieuD.png">
</figure>
<figure class="img">
<img src="images/md.jpg">
</figure>
</div>
</div>
I'm trying to use the classes names "class="nomPositionCourt A">" the target the specific image being hovered on but it doesn't seem to be working.
Here is the JS code:
function over(){
if ( $("#infos").hasClass("A") ){
$("#infos").stop().animate({"margin-left": +0});
$(".img").mouseleave(out);
}
else if ( $("#infos").hasClass("B") ){
$("#infos").stop().animate({"margin-left": +0});
$(".img").mouseleave(out);
}
}
function out(){
$("#infos").stop().animate({"margin-left": -287});
}
At first glance, it looks like the reason is that both of your images are using the same ID tag (which is bad practice).
This is the code I'm looking at:
figure id="infos"
You are using that same ID tag twice. When your code runs, it's picking up the first "infos" tag it comes to, which is your first image.
Make sure to use unique ID tags and this should help resolve your problem.
You have assigned the id attribute to more than one element which suppose to be unique id="infos" class can be assigned to multiple elements but id should be unique
Try this one by changing the id to class
$(".nomPositionCourt").hover(function(){
if ( $(this).hasClass("A") ){
$(this).stop().animate({"margin-left": +0});
$(".img").mouseleave(out);
}
else if ( $(this).hasClass("B") ){
$(this).stop().animate({"margin-left": +0});
$(".img").mouseleave(out);
}
},function(){
$(this).stop().animate({"margin-left": -287});
})
In $(this) you have the object of current hovered image
Here is the Reference

Categories

Resources