Getting parent starting from src attributte - javascript

i need to know if there's a way of getting parent starting with src attributte of img tag . I have something like : 6 draggable objects and 6 dropspots. At every drop i store in a variable src attribute of image i change. With this src i need to find its parrent and set .css("visibility", "visible"). My question : Is there a way to get parent of an img tag starting with its src attribute?
JS FIDDLE: http://jsfiddle.net/FncKS/
Code:
drop: function( event, ui )
{
var dropTarget = event.target.id;
var getSrcChanged = $("#" + dropTarget).children('img').attr("src");
console.log(getSrcChanged);
}
Where console return : ../images/map6.svg (for example)
With this src attributte i would like to make one of draggable objects (the one with same src attributte) visible useing:
var visible = $(dragObjects).children("img").src(getSrcChanged);
$(visible).css("visibility", "visible");
But unfortunately it doesnt work :(
dragObjects its an array : 6 x div.children("img").
Some HTML:
<div class="random drag" id="draggable0">
<img class="svgSize" src="images/map1.svg" draggable="false" />
</div>
<div class="random drag" id="draggable1">
<img class="svgSize" src="images/map2.svg" draggable="false" />
</div>
...
<div class="random drag" id="draggable5">
<img class="svgSize" src="images/map6.svg" draggable="false" />
</div>

I find your scenario very confusing, but it sounds like this is what you want to do:
drop: function( event, ui ) {
var dropTarget = event.target.id,
getSrcChanged = $("#" + dropTarget).children('img').attr("src"),
matchingDraggable = $(dragObjects).find("img[src='"+ getSrcChanged +"'");
matchingDraggable.css("visibility", "visible");
console.log(getSrcChanged);
}
Could you give that a try?

Related

How to get the attribute of the first child of a div?

I have a div
<div id="img-1" class="cards"><img src="blah" alt="blah2"</div>
How do I define a variable that has the value of the alt attribute, without giving img a class or ID?
Thanks!
Try this
const img = document.getElementById('img-1').getElementsByTagName('img')[0];
console.log(img.alt);
document.getElementById('img-1').getFirstElementChild.getAttribute('alt');
You can use getFirstElementChild. As you can see it does not matter what your child element is as long as it exists. But if you are looking for alt you can simply query an img inside the div. alt is an image property.
One way is to use jQuery to select the div by class then find the first img element and get its alt attribute, then store that to a variable:
$(document).ready(function() {
var divCards = $('.cards');
// store the alt attribute of first image to variable
var attrValue = divCards.find('img').eq(0).attr('alt');
console.log(attrValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="img-1" class="cards">
<img src='blah' alt='blah1'>
<img src='blah' alt='blah2'>
</div>
var altValue = document.querySelector('.card > img').alt
for(var each of document.querySelectorAll('.card > img')){
var altValue = each.alt;
....
}
JQuery equivalents
$(`.card > img`).attr('alt')
$(`.card > img`).each(function(index){ // each is bound to this
var altValue = $(this).attr('alt');
});
> forces that the img tag lies directly below the .card element
firstChild.alt should do the trick:
const alt = document.querySelector('.cards').firstChild.alt;
console.log(alt);
<div id="img-1" class="cards"><img src='blah' alt='blah2'></div>
Alternatively you can use the first-child CSS selector:
const alt = document.querySelector('.cards > *:first-child').alt;
console.log(alt);
<div id="img-1" class="cards"><img src='blah' alt='blah2'></div>

JavaScript event handler click thumbnail to enlarge image

So I am very new to Web Design and am having issues getting my click event handler to work.I cant change the html or css files. My task is to set a click handler to my thumbnails to enlarge the image in the img within the <figure> element. While also setting the figcaption text in the figure to the thumbs title attribute. I need to attach to the div id = thumbnails. My script is not enlarging my thumbnails or titles.
This is my created HTML Doc:
<!DOCTYPE html>
<html lang="en">
<head >
<meta charset="utf-8">
<title>Chapter 9 - Share Your Travels</title>
<link rel="stylesheet" href="css/styles.css" />
<script type="text/javascript" src="js/chapter09-project02.js">
</script>
` `</head>
<body>
<header>
<h2>Share Your Travels</h2>
<nav><img src="images/menu.png"></nav>
</header>
<main>
<figure id="featured">
<img src="images/medium/5855774224.jpg" title="Battle" />
<figcaption>Battle</figcaption>
</figure>
<div id="thumbnails">
<img src="images/small/5855774224.jpg" title="Battle"/>
<img src="images/small/5856697109.jpg" title="Luneburg"/>
<img src="images/small/6119130918.jpg" title="Bermuda" />
<img src="images/small/8711645510.jpg" title="Athens" />
<img src="images/small/9504449928.jpg" title="Florence" />
</div>
</main>
</body>
</html>
Js script:
var thumbs = document.getElementById("thumbnails");
thumbs.addEventListener("click", function (e) {
if (e.target.nodeName.toLowerCase() == 'img') {
var clickedImageSource = e.target.src;
var newSrc = clickedImageSource.replace("small", "medium");
var featuredImage = document.querySelector("#featured img");
featuredImage.src = newSrc;
featuredImage.title = e.target.title;
}
});
var img = document.getElementById("figcaption");
img.addEventListener("mouseover",function (event) {
img.className = "featured figcaption";
});
img.addEventListener("mouseout", function (event) {
img.className = "featured figcaption";
var element = document.getElementById('figcaption');
element.style.opacity = "0.9";
element.style.filter = 'alpha(opacity=0%)';
});
Thanks for any advice and hopefully I can pay it forward for someone else!
I think it causes you the problem. The JS is getElementById, but there's no ID is call figcaption.
var img = document.getElementById("figcaption");
The problem is that you are trying to use getElementById to find something with the id of figcaption; nothing on the page has an id of figcaption, so getElementById returns null.
There are a few ways you could fix it:
Add an id to your <figcaption> element: <figcaption id="figcaption">
Instead of using getElementById, use getElementsByTagName: document.getElementsByTagName('figcaption')[0];. (getElementsByTagName always returns a collection of elements, the [0] grabs the first, and in this case only, one in the collection).
Instead of using getElementById, use querySelector like you did to find the featured image element: document.querySelector("#featured figcaption");
This last approach of using querySelector is what I would recommend in this situation; other times it might be better to add an id to the element.
const thumbs = document.getElementById("thumbnails");
const featuredImage = document.querySelector("#featured img");
const caption = document.querySelector("#featured figcaption");
thumbs.addEventListener("click", function (e) {
if (e.target.nodeName.toLowerCase() == 'img') {
var clickedImageSource = e.target.src;
// for the purposes of this demo, I'm using a placeholder
// image service so I need to change the size slightly differently
let newSrc = clickedImageSource.replace("50x50", "350x150");
//var newSrc = clickedImageSource.replace("small", "medium");
featuredImage.src = newSrc;
caption.textContent = e.target.title;
}
});
caption.addEventListener("mouseover",function (event) {
caption.className = "featured figcaption";
});
caption.addEventListener("mouseout", function (event) {
caption.className = "featured figcaption";
// I changed the value to .5 instead of .9 because with such small
// text the opacity change is barely perceivable.
caption.style.opacity = "0.5";
// This is not needed, this was the old way IE used to do it,
// IE < 9 needed it, but IE < 9 is no longer relevant. Just use opacity.
//element.style.filter = 'alpha(opacity=0%)';
});
<header>
<h2>Share Your Travels</h2>
<nav><img src="http://via.placeholder.com/50x50?text=Menu"></nav>
</header>
<main>
<figure id="featured">
<img src="http://via.placeholder.com/350x150" title="Battle">
<figcaption>Battle</figcaption>
</figure>
<div id="thumbnails">
<img src="http://via.placeholder.com/50x50" title="Battle">
<img src="http://via.placeholder.com/50x50/ff0000/ffffff" title="Luneburg">
<img src="http://via.placeholder.com/50x50/00ff00/ffffff" title="Bermuda">
<img src="http://via.placeholder.com/50x50/0000ff/ffffff" title="Athens">
<img src="http://via.placeholder.com/50x50/000000/ffffff" title="Florence">
</div>
</main>
A few things to note about my version, I used let and const instead of var. Both let and const are well supported these days and should be used instead of var unless you need to support very old browsers. I also only query for the caption and featured image elements once and store them in the scope above the click handler, this allows the code inside the click handler to have access to them via closure. This makes everything slightly more efficient since you don't have to query the DOM to find them each time the click handler runs. In this case the performance gain is moot but it is good to be in the habit of writing code as efficiently as possible so you don't have to think about it when it does matter.
Images are void elements, meaning they can't have any content, so you don't need a closing tag. For this reason I used bare <img> tags instead of self-closing <img /> tags. Self-closing images were only ever needed in XHTML, since it was XML, which has a more rigid syntax than HTML. Another thing to note, you don't need the type="text/javascript" on your <script> tags, it just takes up extra space and doesn't really do anything.
I don't understand what you are trying to do with the mouseover and mouseout handlers. Currently what your code does is:
When the mouse moves over the caption, the featured and figcaption classes are added to the caption.
When the mouse leaves the caption, the featured and figcaption classes are again added to the caption and its opacity is set to 0.9, effectively permanently.
I cleaned it up a little in my example to make it more obvious that is what is happening.

Difficulty hiding image with no src

I have a series of the following elements:
<div class="slidetpl">
<img src >
</div>
I want to hide .slidetpl if the image has no source. To do that I have tried the following:
$('.slidetpl img').each(function () {
if (this.src.length == 0) {
$(this).parent().hide();
}
});
But this is not working.
Can anyone point me in the right direction or tell me what I've done wrong?
This does the effect for me:
// Start an immediate invocable function expression, to auto
// execute the internal code and isolate the code from the
// outside JS scope.
(function( $, window, undefined ){
// Find all the document images and iterate over them. In case you like to
// to iterate only under slidetpl change the selector from
// img to .slidetpl img
$( 'img' ).each(
function() {
// If the empty string is equal with the src attribute of
// of the current item in the iteration
if ( '' === $(this).attr('src') ) {
// Then hide the current item in the iteration.
$(this).hide();
}
}
);
})( jQuery, this )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="" />
<img src />
<img src="http://www.iconsdb.com/icons/preview/icon-sets/web-2-orange-2/running-man-xxl.png" />
Note, the above code will hide all the images with empty src attribute. In case you like to hide only the children elements of the .slidetpl then you can modify the selector from img to .slidetpl img.
Try this:
$(document).ready(function(){
$('.slidetpl img[src=""]').parent().hide();
$('.slidetpl img:not([src=""])').parent().show(); //Can be removed.
});
You are very close, just missing the correct syntax of this, refer below:
if ($(this).attr('src').length == 0)
Watch out the demo here.
$('.slidetpl img[src=""]').hide();

Using jQuery to detect if element has a certain style attribute

I'm writing a script to detect whether or not an image is present on a webpage. It's a standard formatting with their html for this section. If there is not an image it looks like
<div id="photo" style="display: none;">
<img id="image" src="IMAGESOURCE" onerror="img2txt()" alt="">
</div>
if there is an image present that same html looks like this
<div id="photo">
<img id="image" src="IMAGESOURCE" onerror="img2txt()" alt="">
</div>
Right now in the script I'm using this, which doesn't work (or i wouldn't be here :D )
var images = ($('#photo[style*="display: none"]').length === 0 ? false : true);
if (images) {
$('#yes[value="Yes"]').click();
}
else {
$('#no[value="No"]').click();
}
(The clicks are for the radio buttons on the form that I am filling out based on this image query)
As of right now the if/else statement is giving the radio "No" a click on a page where it should be a yes. I've tried using
if (!images) {
$('#yes[value="Yes"]').click();
}
else {
$('#no[value="No"]').click();
}
just to see if my boolean was incorrect. But with that adjustment it just does the opposite again. Any help is much appreciated. Thanks
So it is always display:none when not present? jQuery has a specific selector for that :visible.
var present = $("#photo").is(":visible");
To find out whether the image is visible or not:
$('#image:visible').length;
With reference to your own posted code, you could use:
var imageVisible = $('#image:visible').length,
toClick = imageVisible ? 'yes' : 'no';
$('#' + toClick + '[value=' + toClick + ']').click();
Or, avoiding the unnecessary attribute-selectors (given that an id is a unique identifier:
$('#' + toClick).click();
References:
:visible.

javascript - how to get img tags from any element?

I want to get img tags attribute values from any element, img tags could be more than 1, and also can be randomized.
like,
<div> hellow <img src='icons/smile.png' title=':)'> how are u <img src='icons/smile2.png' title=':D'></div>
I want to grab their title attribute values and then want to store in some var currentHTML; with all existing div data.
and then insert into any element just like $('#div').html(currentHTML);
and output should be like this,
hellow :) how are u :D
How can I do this?
Thanks in advance.
Try this:
$("img").each(function()
{
$(this).replaceWith($(this).prop("title"));
});
Fiddle. Its just looping through each image and replacing it (with replaceWith()) with its own title attribute.
UPDATE:
Things got more complex. Check this snippet:
// The text result you want
var currentHTML = "";
// Instead of search for each image, we can search of elements that
// contains images and you want to get their text
$(".images").each(function()
{
// Check note #1
var cloned = $(this).clone().css("display", "none").appendTo($("body"));
// Here we select all images from the cloned element to what
// we did before: replace them with their own titles
cloned.find("img").each(function()
{
$(this).replaceWith($(this).prop("title"));
});
// Add the result to the global result text
currentHTML+= cloned.html();
});
// After all, just set the result to the desired element's html
$("#div").html(currentHTML);
Note #1: Here is what is happening in that line:
var cloned = here we create a var which will receive a cloned element;
the cloned element will the current element $(this).clone();
this element must be hidden .css("display", "none");
and then appended to the document's body .appendTo($("body"));.
Note that in your initial html, the div containing the images received the class images:
<div class="images"> hellow <img src='icons/smile.png' title=':)' /> how are u <img src='icons/smile2.png' title=':D' /></div>
So you can do that on more than one element. I hope this helps.
Here's a neat little function you can reuse.
$(function(){
function getImageReplace($el) {
var $copy = $el.clone();
$copy.find('img').each(function(){
$(this).replaceWith($(this).attr('title'));
});
return $copy.text();
}
//now you can use this on any div element you like
$('#go').click(function() {
alert(getImageReplace($('div')));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div> hellow <img src='icons/smile.png' title=':)'> how are u <img src='icons/smile2.png' title=':D'></div>
<button id='go'>Convert images</button>

Categories