Get Sibling Element of an Image - javascript

So I have
<a href="1.html">
<img src = "image.jpg" class = "picture"/>
<div class="desc"><p>Brief Description</p></div>
</a>
<a href="2.html">
<img src = "image2.jpg" class = "picture"/>
<div class="desc"><p>Brief Description</p></div>
</a>
How do I cycle through the pictures and alter the div accordingly?
So far I have something like:
var pictures = $('.picture');
(var a = 0; a < pictures.size(); a++){
var description = (pictures.get(a)) (.siblings?)(.next?);
//Do what I want with the description
}

You can use Jquery .each() to loop through the elements. And .siblings() to get the sibling of that element.
$('.picture').each(function(){
var description = $(this).siblings('div. desc').text();
// Do what I want with the description
});

notice that .get(a) won't give you a jQuery set, but instead a plain object
https://api.jquery.com/jquery.get/
var pictures = $('.picture');
pictures.each(function() {
var description = $(this).next().html();
//Do what I want with the description
console.log(description);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="1.html">
<img src = "image.jpg" class = "picture"/>
<div class="desc"><p>Brief Description 1</p></div>
</a>
<a href="2.html">
<img src = "image2.jpg" class = "picture"/>
<div class="desc"><p>Brief Description 2</p></div>
</a>

How about selecting the description's <p> directly?
Like this:
$('.picture .desc p')....

You could use next.
$('.picture').each(function(idx, picture){
$(picture).next('.desc'); //this will select div.desc
});

Related

How to add css code in onmouseover="hover('')" [JS]

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).

Conditionally add class to image by jquery

This JS replace image file name default.jpg to hqdefault.jpg from all images below. But now I'm trying to add class to Image, if Image src has img.youtube.com link on images by extending this JS.
JS:
$('#selector img').attr('src',function(i,e){
return $(this).attr('src').replace("default.jpg","hqdefault.jpg");
});
HTML:
<div id="selector">
<img src="http://img.youtube.com/vi/qDc_5zpBj7s/default.jpg">
<img src="http://img.youtube.com/vi/ss7EJ-PW2Uk/default.jpg">
<img src="http://img.youtube.com/vi/ktd4_rCHTNI/default.jpg">
<img src="http://img.youtube.com/vi/0GTXMEPDpps/default.jpg">
</div>
Means, If image src has Youtube image then add a class .video to parent image.
Try:
$('#selector img').each(function(i) {
var self = $(this);
var src = self.attr('src');
if (src.match(/img.youtube.com/)) {
self.attr('src', src.replace("/default.jpg","/hqdefault.jpg"));
self.addClass('video');
}
});
You can add a condition before replacing and add video class.
$('#selector img').attr('src',function(i,e){
if($(this).attr('src').search('img.youtube.com') > 0){
$(this).addClass('video');
}
return $(this).attr('src').replace("default.jpg","hqdefault.jpg");
});

Ascertain the position within a list of elements of the parent of a clicked element

I have a list of elements similar to simplified HTML below. When one of the images is clicked some JavaScript if fired, and the image that is clicked becomes this.theImage.
I now need to get the position of the image; for example if the first image was clicked, the position should be 1, if the second is clicked it should be 2, and so on.
I could use var elements = $('.image-preview', '#gallery');, to take a list of all elements with the image-preview class, and then loop through them and match the ID to the image, but that seems really inefficient.
Is there another way of achieving this task that is more efficient?
<div id="gallery">
<div class="image-preview">
<img id="image-1" src="http://www.mysite.com/image1.jpg" />
</div>
<div class="image-preview">
<img id="image-2" src="http://www.mysite.com/image2.jpg" />
</div>
<div class="image-preview">
<img id="image-3" src="http://www.mysite.com/image3.jpg" />
</div>
<div class="image-preview">
<img id="image-4" src="http://www.mysite.com/image4.jpg" />
</div>
</div>
Not sure I get it, you catch a click on the image like this
$('.image-preview img').on('click', function() {
});
and then to get the index you'd do
$('.image-preview img').on('click', function() {
var index = $('.image-preview img').index(this);
});
note that it's zero based
FIDDLE
You can make Array.prototype.indexOf do it for you:
var gallery = document.getElementById('gallery'),
els = [].slice.call(gallery.getElementsByTagName('img'));
gallery.onclick = function(e) {
if(e.target.tagName.toLowerCase() !== 'img') return;
var position = els.indexOf(e.target);
};
Demo

Assign img' src dynamically

The page will display an image's url text correctly. But I am not sure how to assign the message to the img 's src to display the image.
<DIV class="msgStyle1" id="message">Waiting for image</DIV>
<div class="imgStyle1" id="message">
<img src=whatneedtogohere /></div>
function displayText(text) {
console.log(text);
document.getElementById("message").innerHTML=text;
window.castReceiverManager.setApplicationState(text);
};
Fixed HTML (switched classes and IDs to make IDs unique) and added an image ID for simplicity:
<div id="msgStyle1" class="message">Waiting for image</div>
<div id="imgStyle1" class="message">
<img src="" id="image" />
</div>
JS:
document.getElementById('image').src = 'http://yourImagePathHere';
See it work here: http://jsfiddle.net/N3rCm/
First off, you shouldn't have multiple Id's on the page, it'll mess with your JS.
Next I would give your image a class if you can
//jquery example of what you would do
var imgSrc = 'http://wherever/youre/getting/this/from';
$('.myimageclass').attr('src', imgSrc);
//non jquery
var myImg = document.getElementsByClassName('myimageclass')[0]; //assuming it's the first one
//or if you can uniquely identify it
var myImg = document.getElementById('imgId');
myImg.src = imgSrc;

Getting the src attribute of an image within a parent tag

I have a list of images, one of which gets a class="selected" after a change occurs on the page:
<div id="selectable">
<li>
<img src="\images\1.jpg" />
</li>
<li class="selected">
<img src="\images\2.jpg" />
</li>
<li>
<img src="\images\3.jpg" />
</li>
</div>
I want to be able to capture the value of the image's src attribute, so I can use it later...
I'm thinking something like this:
$("#selectable").change(function() {
var src = $('li[class="selected"]').attr('src');
alert("source of image with alternate text = example - " + src);
}
But I need it to get the value of the src attribute of the child element (img).
$("li.selected").find("img").attr("src");
You can do this using below code.
var src = $('li.selected img').attr('src');
-------------^^^^^^^^^^^^^^^--------
I want to be able to capture the value of the image's src attribute, so I can use it later...
var src = ''; // DEFINE VARIABLE OUTSIDE
$('#selectable li').click(function(){ // USE CLICK EVENT
src = $('img', this).attr('src');
// alert( src )
});
To target directly the desired image use:
// some event
$('#selectable li.selected img').attr('src');
//
var imgsrc="";
$("#selectable li").click(function() {
var imgsrc= $('li.selected img').attr('src');
alert( imgsrc);
}
Change
var src = $('li[class="selected"]').attr('src');
to
var src = $('li[class="selected"]').find('img').attr('src');
More on jQuery find
You need to do something like this:
var src=$('#selectable > li.selected > img').attr('src');
alert("source of image with alternate text = example - " + src);
An example
HTML:
<div id="selectable">
<li>
<img src="\images\1.jpg" />
</li>
<li class="selected">
<img src="\images\2.jpg" />
</li>
<li>
<img src="\images\3.jpg" />
</li>
</div>
Javascript:
$('#selectable li').click(function(){
$(this).addClass('selected');
var src = $(this).children('img').attr('src');
alert("source of image with alternate text = example - " + src);
});
See Jquery selector techniques for more details:
http://api.jquery.com/category/selectors/

Categories

Resources