How to make a certain div visible while hovering an image? - javascript

<div class="parent">
<div class="parent.child">
<div class="parent.chil.child">
<div class="parent.chil.child.child">
<img src ="link0" >
<img src ="link1" >
<img src ="link2" >
</div>
</div>
</div>
<h4>
text
</h4>
<div class="imgClass0">
<p>some text</p>
</div>
<div class="imgClass1">
<p>some text</p>
</div>
<div class="imgClass2">
<p>some text</p>
</div>
Hey guys !
I have a problem. I have a div whithin I can have one or more <img> nodes, depends how the server generates the DOM (there can be one or many, depends on a number from the database.
There are several <div> elements under the <h4> node, the number of them is equal to the number of <img> elements from above.
I need help in making a javascript that makes "imgClass1" visible when I hover <img src ="link1" >, and the other imgClassX, X=(1..n) invisible, and so on. I give them default visibility display:none, but I need imgClass0 to have default visibility:visible.
Best regards,
iusmar.

You can attribute starts with selector along with :eq() selector:
$('img[src^=link]').hover(function() {
var idx = $(this).index();
$('div[class^="imgClass"]:eq(' + idx + ')').show();
}, function() {
var idx = $(this).index();
$('div[class^="imgClass"]:eq(' + idx + ')').hide();
});
Fiddle Demo

try like this
$("img[src=link1]").hover(function(){
$("div[class^='imgClass']").hide();
$(".imgClass1").show();
});
fiddle

First, you should put a class on your images to use as a selector. You should also put the image ID as a data attribute on the tags. This will allow you to easily assign an event handler when hovering these images, and also easily extract the image ID:
<img src="link0" class="yourImages" data-image-id="0">
<img src="link1" class="yourImages" data-image-id="1">
<img src="link2" class="yourImages" data-image-id="2">
You could also apply that ID to the divs:
<div class="images" data-image-id="0">
<p>some text</p>
</div>
<div class="images" data-image-id="1">
<p>some text</p>
</div>
<div class="images" data-image-id="2">
<p>some text</p>
</div>
Then you can bind a hover handler to the yourImages class, get the ID from the hovered element, hide all image divs then show only the required one:
$('.yourImages').hover(function() {
var imageID = $(this).data('image-id');
$('.images').hide();
$('.images[data-image-id="' + imageID + '"]').show();
}, function() {
$('.images').hide();
});
What do you want to do when you stop hovering over any images? My example just hides them all again.

Add a class / id just like following for the images
<img class="img0" src ="link0" >
<img class="img1" src ="link1" >
<img class="img2" src ="link2" >
and try the following javascript
$("img").hover(function (){
var cls=$(this).attr("class");
$("div[class^='imgClass']").hide();
var visibleCls=".imgClass"+(parseInt(cls.replace("img","")));
$(visibleCls).show();
});

Related

JS / jQuery - How together innerHTML of targeted element of a certain class and append /replace it?

I want to get the text on click with a certain class but nothing works. I have a div with 2 p tags and I want to get both separate. Also, I want to append them. .append() appends but just keeps adding all targeted events. empty().append() gives me random results (on first click it works, on second I get half of the text etc). Ive tried most of what I could find on stack overflow but nothing helped. Any help would be great!
Ive tried:
$(event.target).text(); //that gives me the text, but not both p elements separate
$(this).hasClass('.video-title'); //only returns to me true/false
var title= document.getElementsByClassName("video-title")[0].innerHTML; //doesn't give me the current element.
$('p.video-title').innerHTML; //doesnt help either
HTML
<div class="video-container">
<iframe id="vid_frame" src="https://www.youtube.com/embed/xxx?rel=0&showinfo=0&autohide=1" width="900" height="450"></iframe>
<div id="video-info"></div>
</div>
<div class="col-sm-4 video-col">
<div class="video-wrapper" onClick="attachSrc('yyy', event)">
<img src="assets/images/thumbnail/yourHeart_official.jpg" width="260" height="160">
<div class="overlay">
<p class="video-title">title 1</p>
<p class="video-author">author 1</p>
</div>
</div>
</div>
<div class="col-sm-4 video-col">
<div class="video-wrapper" onClick="attachSrc('xxx', event)">
<img src="assets/images/thumbnail/yourHeart_karaoke.jpg" width="260" height="160">
<div class="overlay">
<p class="video-title">title 2</p>
<p class="video-author">author 2</p>
</div>
</div>
</div>
<script>
function attachSrc(id, event) {
var text = $(event.target).text();
$('#video-info').append(text);
}
</script>
As you are using jQuery, I would recommend you to use unobtrusive event handler and use .on() to attach event handlers.
Here in example I have attached event with wrapper element and DOM traversal method to traverse and target desired element.
And to persists arbitrary data use data-* prefixed custom attribute which can be fetched using .data(key)
<div class="video-wrapper" data-id="yyy">
Script
$('.video-col').on('click', '.video-wrapper', function() {
var elem = $('#video-info').empty();
var title = $(this).find('.video-title').text();
elem.append(title);
console.log(title);
var author= $(this).find('.video-author').text();
elem.append(author);
console.log(author);
console.log($(this).data('id'));// To fetch custom data associated with element
});
$(function() {
$('.video-col').on('click', '.video-wrapper', function() {
console.clear();
var elem = $('#video-info').empty();
var title = $(this).find('.video-title').text();
elem.append(title);
console.log(title);
var author = $(this).find('.video-author').text();
elem.append(author);
console.log(author);
console.log($(this).data('id')); // To fetch custom data associated with element
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="video-container">
<div id="video-info"></div>
</div>
<div class="col-sm-4 video-col">
<div class="video-wrapper" data-id="yyy">
<img src="assets/images/thumbnail/yourHeart_official.jpg" width="260" height="160">
<div class="overlay">
<p class="video-title">title 1</p>
<p class="video-author">author 1</p>
</div>
</div>
</div>
<div class="col-sm-4 video-col">
<div class="video-wrapper" data-id="xxx">
<img src="assets/images/thumbnail/yourHeart_karaoke.jpg" width="260" height="160">
<div class="overlay">
<p class="video-title">title 2</p>
<p class="video-author">author 2</p>
</div>
</div>
</div>

Target parent element within a child element's onclick event hander

Is it possible to target the ID of a parent div with an event handler in javascript?
Given the following code, when you click the image an alert fires containing the ID of the image "two". Is it possible to return "one", which is the ID of the parent div, appear in this box instead?
<div id="one">
<p>Some Text</p>
<img src="http://placehold.it/48x48" alt="" id="two" onclick="random(id)" />
</div>
<script>
function random(id) {
alert("working" + " " + id);
}
</script>
You can do this.parentNode to get a reference to the parent node. Then you can get its ID with .id. So alert(this.parentNode.id) should work.
<div id="one">
<p>Some Text</p>
<img src="http://placehold.it/48x48" alt="" id="two" onclick="random(this)" />
</div>
<script>
function random(node) {
alert("working" + " " + node.parentNode.id);
}
</script>

Jquery pass this.Text() as identifier

Basically im just trying to get the value of this.Text() and edit css of all class with that value.
<div>
<img class="First" style="display:none">
<img class="Second" style="display:none">
<img class="Third" style="display:none">
<p><span class="firstWord">First</span> phrase</p>
</div>
<div>
<img class="First" style="display:none">
<img class="Second" style="display:none">
<img class="Third" style="display:none">
<p><span class="firstWord">Second</span> phrase</p>
</div>
<div>
<img class="First" style="display:none">
<img class="Second" style="display:none">
<img class="Third" style="display:none">
<p><span class="firstWord">Third</span> phrase</p>
</div>
Im using this code to get the first word but im a bit lost on how to pass this.Text as indentifier. Im just trying to unhide an image with a class the same with the value of this.Text() :
$('.firstWord').each(function() {
fwtext = $(this).text();
$('#' $fwtext).css("display", "block");
});
The div and all tags inside it are dynamically generated and repeated so i cant simply go on editing them.
THANK YOU SO MUCH EVERYONE FOR HELPING.
This is wrong:
$('#' + $fwtext)
//-----^
Add a + for concatenation. Also since you are using a class and not an id, you must use . instead of #:
$('.' + $fwtext)
Your img tags have a class, not an id. So your jQuery selector should look like: $("." + fwtext). And yes - it will display necessary image only in corresponding div. jsFiddle for testing.
$(".firstWord").each(function () {
var fwtext = $(this).text();
var currentBlock = $(this).parents("div");
currentBlock.find("." + fwtext).show();
});
Remove the $ sign and add + in place of it
$('#'+ fwtext).css("display", "block");
based on your comment here is the edit
$('.firstWord').each(function() {
$('<div></div>').text($(this).text()).css("display", "block");
});

Passing a DOM element to a javascript function

I want to run a generic javascript function with an element, sometimes multiple elements in the same HTML document. It seems to me the easiest way is to call the function from inside a DOM element. OK here's the problem. "this" refers the window element and I have seen how scope works for functions using "this" but I don't see how to get "this" to refer to an element.
I could do getElementById but I want a fairly generic javascript and not have to come up with unique IDs everytime I want to use it. getElementsByClasses may be a workaround but it just seems there should be an easier way to do this without relying on id's or classes.
The HTML
</HEAD>
<BODY>
<div id="content">
<div class="linksbox">
<a href="https://www.corponline.org" target="_blank">
<div class="linkicon">
<img src="asislink.jpg">
</div>
</a>
<div class="linkblurb">
<h2>National</h2>
<p>Description of link</p>
</div>
<script>valignimg();</script>
</div>
</div> <!-- End content -->
</BODY>
</HTML>
The javascript. It's dh and ih that I need to pass to the function.
function valignimg() {
dh = /* div element */
ih = /* image (child element) */
topmargin = (dh.offsetHeight - ih.offsetHeight)/2;
return topmargin;
}
If you're not calling it from one of the elements (i.e. via event handler), you're going to have to use a selector of some kind, either ID or class as you highlighted, or name or tag name if that can work, or some combination. Somewhere along the way it will need to be specified. In even though you weren't keen on using class, that's likely your best option so I've highlighted it in this first example.
//warning - this event isn't supported on some older browsers like IE8
document.addEventListener("DOMContentLoaded", function(event) {
valignAll();
});
function valignimg(dh) {
//Only added the IDs for this purpose, not using them to select elements so there's no functional requirement for them.
console.log(dh.id);
//This supposes that you know the image tag you want is always the first img element among dh's children.
ih = dh.getElementsByTagName('img')[0];
console.log(ih.alt);
var topmargin = (dh.offsetHeight - ih.offsetHeight) / 2;
console.log('dh.offsetHeight = ' + dh.offsetHeight);
console.log('ih.offsetHeight = ' + ih.offsetHeight);
console.log('topmargin = ' + topmargin);
ih.style.marginTop = topmargin + "px";
console.log('ih.style.marginTop = ' + ih.style.marginTop);
}
function valignAll(){
var linkIcons = document.getElementsByClassName('linkicon');
for(i = 0;i < linkIcons.length;i++){
valignimg(linkIcons[i]);
}
}
<BODY>
<div id="content">
<div class="linksbox">
<a href="https://www.corponline.org" target="_blank">
<div id="icon1" class="linkicon">
<img alt="img1" src="http://placehold.it/20x20">
</div>
</a>
<div class="linkblurb">
<h2>National</h2>
<p>Description of link</p>
</div>
<a href="https://www.corponline.org" target="_blank">
<div id="icon2" class="linkicon">
<img alt="img2" src="http://placehold.it/21x20">
</div>
</a>
<div class="linkblurb">
<h2>National</h2>
<p>Description of link</p>
</div>
<a href="https://www.corponline.org" target="_blank">
<div id="icon3" class="linkicon">
<img alt="img3" src="http://placehold.it/22x20">
</div>
</a>
<div class="linkblurb">
<h2>National</h2>
<p>Description of link</p>
</div>
</div>
</div>
<!-- End content -->
</BODY>
You can see, although my usage is pretty rudimentary, I've used getElementsByTagName as well, calling from a parent element other than document. The IDs I've added aren't used for locating anything, I'm just using them so that when I log to console you can see which element it really is, the same as with my horrendous misuse of the alt attribute on the images.
If you know that your only image elements on the page are the ones you're acting on, then maybe starting with document.getElementsByTagName('img') is the approach for you, and then get the div with the .parentNode property. This would remove the reliance on classes, but if you add other img tags to the page then you'd need some way to identify from each one whether it's once you want to run your align function against or not. The img tags you want to access have a common ancestor or parent that no other img tags do. I've added another snippet below that shows this. And you could combine these two approaches with a nest loop to get all img tags within multiple divs that all share a class, for example.
//warning - this event isn't supported on some older browsers like IE8
document.addEventListener("DOMContentLoaded", function(event) {
valignAll();
});
function valignimg(ih) {
//Only added the IDs for this purpose, not using them to select elements so there's no functional requirement for them.
console.log(ih.alt);
//This supposes that you know the image tag you want is always the first img element among dh's children.
dh = ih.parentNode;
console.log(dh.id);
var topmargin = (dh.offsetHeight - ih.offsetHeight) / 2;
console.log('dh.offsetHeight = ' + dh.offsetHeight);
console.log('ih.offsetHeight = ' + ih.offsetHeight);
console.log('topmargin = ' + topmargin);
ih.style.marginTop = topmargin + "px";
console.log('ih.style.marginTop = ' + ih.style.marginTop);
}
function valignAll(){
//if they're the only img tags on the page,
//document.getElementsByTagName('img'); will work fine.
//lets assume they aren't.
var images = document.getElementsByClassName('linksbox')[0].getElementsByTagName('img');
//I can grab the comment parent/ancestor by whatever means available, and then grab just its decendants by tag name.
alert(images);
for(i = 0;i < images.length;i++){
valignimg(images[i]);
}
}
<BODY>
<div id="content">
<img src="http://placehold.it/240x20"><< Some sort of header logo
<div class="linksbox">
<a href="https://www.corponline.org" target="_blank">
<div id="icon1" class="linkicon">
<img alt="img1" src="http://placehold.it/20x20">
</div>
</a>
<div class="linkblurb">
<h2>National</h2>
<p>Description of link</p>
</div>
<a href="https://www.corponline.org" target="_blank">
<div id="icon2" class="linkicon">
<img alt="img2" src="http://placehold.it/21x20">
</div>
</a>
<div class="linkblurb">
<h2>National</h2>
<p>Description of link</p>
</div>
<a href="https://www.corponline.org" target="_blank">
<div id="icon3" class="linkicon">
<img alt="img3" src="http://placehold.it/22x20">
</div>
</a>
<div class="linkblurb">
<h2>National</h2>
<p>Description of link</p>
</div>
</div>
</div>
Sponsor Logos or Site Certs in the footer
<img src="http://placehold.it/20x20"><img src="http://placehold.it/20x20"><img src="http://placehold.it/20x20">
<!-- End content -->
</BODY>

jQuery Newbie, need a little help

Okay, so I am in the process of recreating this feature:
http://www.w3.org/html/logo/#the-technology
I current have it so when you click on a link, it will add a class to the image that relates to that link (href="#one" on the <a> and then id="#one" on the <img>), however it is currently not going through each <a> tag and only one. And also it is not removing the class I requested.
Code follows:
JS
$(document).ready(function() {
var container = '#portfolio #text_container';
var img_container = '#portfolio #image_container';
$(container).children('a').bind('click', function() {
var this_attr = $(this).attr('href');
var this_img = $(img_container).find('img').attr('id');
if(this_attr == this_img) {
//$(img_container).find('img').hasClass('current').removeClass('current');
// ^^^ This line isn't working, any ideas? :/
$(img_container + ' img[id*="' + this_attr + '"]').addClass('current');
}
else {
alert(this_img + ' this img');
alert(this_attr + ' this attr');
}
});
});
And the HTML is as follows
<div id="portfolio">
<div id="image_container">
<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" alt="" class="current" id="#one" />
<img src="http://static.jquery.com/files/rocker/images/btn_downloadLarge.gif" alt="" id="#two" />
</div>
<div id="text_container">
Item 1
Item 2
<p id="#one" class="current">A bunch of text!</p>
<p id="#two">The second bunch of text!</p>
</div>
</div>
Please let me know if you need any more information :)
rcravens fixed this with the following code..
JS
$(document).ready(function() {
$('#text_container a').click(function(evt) {
evt.preventDefault();
$('.current').removeClass('current');
var href = $(this).attr('href');
$("." + href).addClass('current');
});
And the HTML..
<div id="portfolio">
<div id="image_container">
<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" alt="" class="one current" />
<img src="http://static.jquery.com/files/rocker/images/btn_downloadLarge.gif" alt="" class="two" />
</div>
<div id="text_container">
Item 1
Item 2
<p class="one current">A bunch of text!</p>
<p class="two">The second bunch of text!</p>
</div>
</div>
My interpretation of what you are trying to do is here:
http://jsfiddle.net/rcravens/wMhEC/
The code is changed a bit. You shouldn't have multiple elements with the same id.
Bob
The reason this isn't working:
if(this_attr == this_img)
is because this_attr is a URL and this_img is an ID attribute value.

Categories

Resources