Trouble accessing child divs in jquery - javascript

I have multiple divs and I'm attempting to do a function when a user mouses over the divs. Inside of the divs there can be any number of "child" divs and I need to access them within the function. I don't seem to be able to do this. Here is an example of what I'm trying to do:
<div id='div_test' onmouseover='modelMouseOver2()' onmouseout='modelMouseOut()'>
<div id = "model1"><img src="img/circle.png" alt="" /></div>
<div id = "model2" class='models' onmouseover="modelMouseOver2()" onmouseout="model2MouseOut()" style=" width: 40px; height: 40px;"><img src="img/circle2.png" alt="" />
<div><img src="img/circle3.png" alt="" /></div>
<div><img src="img/circle4.png" alt="" /></div>
<div><img src="img/circle2.png" alt="" /></div>
</div>
<div id = "model3" class='models' onmouseover="modelMouseOver2()"><img src="img/circle3.png" alt="" /></div>
<div id = "model4" class='models' onmouseover="modelMouseOver2()"><img src="img/circle4.png" alt="" /></div>
<div id = "model5" class='models' onmouseover="modelMouseOver2()"><img src="img/circle5.png" alt="" /></div>
</div>
for The script:
function modelMouseOver2() {
// I'm not sure what to do here to access the child divs.
$(this).children("div").each(function (i) {
$(this).hide();
});
}

Try to use find()
$(this).find("div").hide();
But if you started using jQuery you may subscribe to your events on document load using jQuery itself:
$(function() {
$('div#div_test').hover(function() {
$(this).find('div').hide();
}, function() {
$(this).find('div').show();
});
});

try a js like this
(function($){
$('#div_test').hover(
function(){
// this is the mouse over
// this selects all the div inside
$(this).find('div');
},
function(){
// this is the mouse out
// this selects all the div inside
$(this).find('div');
}
);
})(jQuery);

You can do some thing like this
$(this).find("div").each(function () {
$(this).hide();
});

The problem is that in:
function modelMouseOver2() {
// I'm not sure what to do here to access the child divs.
$(this).children("div").each(function (i) { // here
$(this).hide();
});
}
The first "this" refers to the DOM window.
You have two options here. The first is to pass in this in the inline event, the second being just to set the event in javascript:
Inline:
<div id='div_test' onmouseover='modelMouseOver2(this)' onmouseout='modelMouseOut()'>
and the javascript for inline:
function modelMouseOver2(xthis) {
// I'm not sure what to do here to access the child divs.
$(xthis).children("div").each(function (i) {
$(this).hide();
});
}
Or, setting the onmouseover via javascript:
document.getElementById('div_test').onmouseover=modelMouseOver2;

Related

How to make change the height of all images inside a div?

How to make change the height of all images inside a div?
I have
$('.images img').each(function() {
$('img').attr('height', element.parent().attr('imgheight'));
});
<div imgheight="300px" class="images">
<img src=" http://www.yu51a5.com/wp-content/uploads/2015/01/goldenhorseman.jpg " />
<img src=" http://www.yu51a5.com/wp-content/uploads/2015/01/bronze-horseman.jpg " />
</div>
It does not seem to do anything - see https://jsfiddle.net/yu51a5/527gn64n/4/. How to make it work?
I cannot use "height=100%" because normally these images come with captions, so the image should be shorter that the div.
You haven't defined element. Access the node from inside the each function.
$('.images img').each(function(i, node) {
$('img').attr('height', $(node).parent().attr('imgheight'));
});
Working fiddle.
I suggest you to use HTML5 data- attribute with your custom attribute imgheight
<div data-imgheight="300px" class="images">
<img src=" http://www.yu51a5.com/wp-content/uploads/2015/01/goldenhorseman.jpg " />
<img src=" http://www.yu51a5.com/wp-content/uploads/2015/01/bronze-horseman.jpg " />
</div>
And JS can be as easy as this:
$('.images > img').css('height', $('.images').data('imgheight'));
Check fiddle
But, if you have multiple .images div, you would do like this
$('.images img').each(function() {
$(this).css('height', $(this).closest('.images').data('imgheight'));
});
or better
$('.images').each(function() {
$(this).find('img').css('height', $(this).data('imgheight'));
});
Change element to $(this) and you're good.
https://jsfiddle.net/wh85afq7/
Change the 2 references within the each function to the images to $(this)...
$('.images img').each(function() {
$(this).css('height', $(this).parent().attr('imgheight'));
});
You can use data-height attribute and get value by element.data("height")
here is the working example below
$( document ).ready(function() {
$('.images img').each(function() {
$(this).attr('height',$('.images').data("height"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-height="300px" class="images">
<img src="http://www.yu51a5.com/wp-content/uploads/2015/01/goldenhorseman.jpg" />
<img src="http://www.yu51a5.com/wp-content/uploads/2015/01/bronze-horseman.jpg" />
</div>

Change image when div click

I have a div act like button that contain an image. I want when I click the div the image inside it will change I put a jquery but my jquery only work in 1 way it can switch to second image but cant switch back to first image.
HTML :
<div class="post-like m-30">
<img class="img-responsive" src="img/like.png" alt="">
<h4 class="bold text-center capital">appreciate this!</h4>
</div>
CSS :
.post-like{
cursor: pointer;
}
.post-like img{
margin: auto;
}
JS :
$(document).ready(function() {
$('.post-like').click(function(){
$(".post-like img").attr('src',"img/like.jpg");
return false;
});
});
Can you teach me why my jquery didnt work?
To toggle between the both src attributes, you could add condition in your click event :
$(document).ready(function() {
$('.post-like').click(function(){
var src = $(".post-like img").attr('src');
if(src=="https://upload.wikimedia.org/wikipedia/commons/2/2f/MRT_Singapore_Destination_1.png")
$(".post-like img").attr('src',"https://upload.wikimedia.org/wikipedia/commons/1/10/MRT_Singapore_Destination_2.png");
else
$(".post-like img").attr('src',"https://upload.wikimedia.org/wikipedia/commons/2/2f/MRT_Singapore_Destination_1.png");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="post-like m-30">
<img class="img-responsive" src="https://upload.wikimedia.org/wikipedia/commons/2/2f/MRT_Singapore_Destination_1.png" alt="">
<h4 class="bold text-center capital">appreciate this!</h4>
</div><!-- post-like -->
Grab the value of the src attribute and store it in a variable. Use this variable as your reference in an if statement to determine which image to switch to:
$(document).ready(function() {
$('.post-like').click(function(){
var img=$(this).attr('src');
if(img=="img/like.jpg"){
$(".post-like img").attr('src',"img/like.jpg");
return false;
}else{
$(".post-like img").attr('src',"img/otherimage.jpg");
return false;
}
});
});
There was nothing wrong with your code, it changed the source just fine.
In order to create a 'click to toggle'-flow, you need to know both sources, I tend to do this by having two variables (one with the 'special' source and one empty, which is set on first use).
$(function() {
var specialSrc = 'http://lorempixel.com/image_output/nightlife-q-g-160-100-10.jpg',
img = $('.post-like img'),
normalSrc;
$('.post-like').click(function(){
var src = img.attr('src');
if (!normalSrc) {
normalSrc = src;
}
img.attr('src', src === normalSrc ? specialSrc : normalSrc);
return false;
});
});
.post-like{
cursor: pointer;
}
.post-like img{
margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="post-like m-30">
<img class="img-responsive" src="http://lorempixel.com/image_output/nightlife-q-c-160-100-4.jpg" alt="">
<h4 class="bold text-center capital">appreciate this!</h4>
</div><!-- post-like -->
I've also stored the image in the img variable, so you don't need to look for it every click, and I've replace $(document).ready(function() {..}) with the shorter syntax $(function() {..}) which does the same thing)
make it simpler and do toggle
$(".post-like").click(function() {
$(this).find('img').toggle();
});
TOGGLE

Reload a DIV on click of another DIV

I have a div called masterdiv, inside this div there are 3 other div div1, div2, and div3,
This is the html for these html:
<div id="masterdiv" class="masterdivclass">
<div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>
</div>
I also have another div:
<div id=”reload”><img src="reload.png" width="200" height="70" onclick=loadDIV();></div>
What I’m trying to do is to reload the masterdiv div whenever the reload div is clicked on. Hiding and then showing the div isn’t enough as I need the content to be reloaded when the refresh div is clicked on. I don’t want to reload the entire page, just the masterdiv which contains the 3 other div. But I’m not certain this is possible.
I’m trying to do it with this Javascript function:
<script type="text/javascript">
function loadDiv(){
$("<div id="masterdiv" class="masterdivclass">
<div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>
</div>").appendTo("body");
}
</script>
This isn’t working, I think maybe I'm going about this in the wrong way? Maybe I’m missing something very simple here? I’d really appreciate any help with this, thank you in advance!
UPDATE
After reconsidering my project's requirements, I need to change part of my question, I now need to randomise the images displayed in the divs, and have a new random image load every time the reload div is clicked on. I also need to remove each class that’s currently in each of the three divs and then reattach the same classes to the divs (if I don’t remove and reattach the classes then the divs just display the plain images without any class/effect applied to them, it seems like I need to reload the class every time I load an image into a div in order for the class/effect to be applied successfully).
I have 5 images, and I’m using each div’s id tag to attach a random image to each div.
First I’m assigning the 5 different images to 5 different ids:
<script>
document.getElementById('sample1').src="images/00001.jpg";
document.getElementById('sample2').src="images/00002.jpg";
document.getElementById('sample3').src="images/00003.jpg";
document.getElementById('sample4').src="images/00004.jpg";
document.getElementById('sample5').src="images/00005.jpg";
</script>
And then I’m trying to use the following Javascript to load a randomised id (and its assigned image) to each of the 3 divs when the reload div is clicked:
<script>
$(function() {
$('#reload').on('click',function(){
$("#masterdiv").find("div[id^='div']").each(function(index){
//First, remove and reattach classes “div1class”, “div2class” and “div3class”
//from “easyDIV”, “mediumDIV” and “hardDIV” respectively:
$(“#easyDIV”).removeClass('div1class');
$(“#easyDIV”).addClass('div1class');
$(“#mediumDIV”).removeClass('div2class');
$(“#mediumDIV”).addClass('div2class');
$(“#hardDIV”).removeClass('div3class');
$(“#hardDIV”).addClass('div3class');
//Get a random number between 1 and 5, then attach it to “sample”,
//so that the result will be either “sample1”, “sample2”, “sample3”, “sample4” or “sample5”,
//call this variable “variablesample”:
var num = Math.floor(Math.random() * 5 + 1);
variablesample = "sample" +num;
//Attach this randomised id to all three divs using “variablesample”:
jQuery(this).prev("easyDIV").attr("id",variablesample);
jQuery(this).prev("mediumDIV").attr("id",variablesample);
jQuery(this).prev("hardDIV").attr("id",variablesample);
});
var p = $("#masterdiv").parent();
var el = $("#masterdiv").detach();
p.append(el);
});
});
</script>
I’m trying to make it so that all 3 divs will show the same randomised picture (that’s why they’re all sharing the variable “variablesample”), and each div will reload its own class/effect (div1class, div2class and div3class) but it’s not working. I’m not sure if it’s correct to use jQuery inside a Javascript function, or if my syntax for updating the ids of the divs is incorrect.
Perhaps my logic to solving this problem is all wrong? I’d really appreciate any more help with this problem. Thanks again in advance!
Original question was edited many times, so here is the correct answer for the latest edit. Answer to the question; "How to use random image, but same image on all 3, and 3 class on/off switching":
$(function() {
var imageArray = [
'https://via.placeholder.com/40x40',
'https://via.placeholder.com/80x40',
'https://via.placeholder.com/120x40',
'https://via.placeholder.com/160x40',
'https://via.placeholder.com/200x40'];
reloadImages(imageArray);
$('#reload').on('click',function(){
$( "#masterdiv img[id^='div']" ).each(function(index){
$(this).removeClass("div"+(index+1)+"class");
$(this).fadeOut( "slow", function() {
if(index==0) {
reloadImages(imageArray);
}
$(this).addClass("div"+(index+1)+"class");
$(this).fadeIn();
});
});
});
});
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function reloadImages(array){
shuffleArray(array);
for(var i=0;i<3;i++){
// places the first image into all divs, change 0 to i if you want different images in each div
document.getElementById('div'+(i+1)+'id').src=array[0];
}
}
.div1class {
border:2px dashed #0F0;
}
.div2class {
border:2px dashed yellow;
}
.div3class {
border:2px dashed red;
}
#reload {
background-color:blue;
color:white;
width:100px;
height:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='reload'>Click here</div>
<div id="masterdiv" class="masterdivclass">
<div id="div1">
<img src="https://via.placeholder.com/20x40" class="div1class" id="div1id" />
</div>
<div id="div2">
<img src="https://via.placeholder.com/20x40" class="div2class" id="div2id" />
</div>
<div id="div3">
<img src="https://via.placeholder.com/20x40" class="div3class" id="div3id" />
</div>
</div>
Line breaks and un-escaped quotes are why the functions is not working.
function loadDiv(){
$('#masterdiv').remove();
$("<div id='masterdiv' class='masterdivclass'><div id='div1'><img class='div1class' src='image1.jpg' id='div1id' /></div><div id='div2'><img class='div2class' src='image2.jpg' id='div2id' /></div><div id='div3'><img class='div3class' src='image3.jpg' id='div3id' /></div></div>").appendTo("body");
}
try:
function loadDiv(){
$("#masterdiv").load(location.href + " #masterdiv");
}
Here's the code pen demo:
http://codepen.io/anon/pen/xwgRWm
If content of container is not being changed dynamically then there is no point reloading it. appendTo wiil append DOM in existing DOM structure, you will need html() here which will replace the content inside container. Also note you had typo here onclick=loadDiv();
HTML:
<div id="masterdiv" class="masterdivclass">
<div id="div1"><img class="div1class" src="image1.jpg" id="div1id"/></div>
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id"/></div>
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id"/></div>
</div>
<div id="reload"><img src="reload.png" width="200" height="70" onclick=loadDiv();></div>
JS:
function loadDiv() {
$("#masterdiv").html('<div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>\
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>\
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>');
}

how to make toggled title stay after mouse out function is complete?

Please see this fiddle http://jsfiddle.net/rabelais/Fzs7u/
I have thumbnails and titles that toggle when a mouseover function occurs. How can I make the title remain from the last hovered thumbnail? Should I use something other than toggle? Perhaps target the css display rule?
$(".thumbnail-wrapper").on("mouseover mouseout", "img", function () {
$("#" + $(this).data("title")).toggle();
});
Since you don't want to hide the caption, I'd do things a little differently:
http://jsfiddle.net/zZ6UJ/
<div class="editable title" id="title">
</div>
<div class="thumbnail-wrapper repeatable">
<img src="http://intelligen.info/images/LFW Live Show Drawings/Vivienne Westwood/2013/img012_2.jpg" alt="1" data-title="Vivienne Westwood"/>
</div>
<div class="thumbnail-wrapper repeatable">
<img src="http://intelligen.info/images/LFW Live Show Drawings/Vivienne Westwood/2013/img013_3.jpg" alt="2" data-title="Paul Smith"/>
</div>
$(".thumbnail-wrapper").on("mouseover", "img", function () {
$("#title").text($(this).data('title'));
});
http://jsfiddle.net/Fzs7u/3/
$(".thumbnail-wrapper").on("mouseover", "img", function () {
$('.title:visible').hide();
$("#" + $(this).data("title")).show();
});
I changed your .toggle() to .show(), and hid .title on mouseover, to make sure that only one title is displayed at a time. Also removed your mouseout handler.

JavaScript Fade In/Out issues

I am having some difficulty trying to get my Fade In and out effect working properly. I think I am over complicating it.
I have 4 images, however only the first 2 need to be faded out and in on hover of the image (The other 2 images come into play with some other feature on the page).
My HTML is:
<div class="square">
<div class="imageHolder">
<!--Comment out and uncomment BG image to show transitions on BG images-->
<img class="one" src="image_01.jpg" />
<img class="two" src="image_02.jpg" />
<img class="three" src="image_03.jpg" />
<img class="four" src="image_04.jpg" />
</div>
</div>
Images, two, three, four are displayed none
JS:
$('.square').mouseover(function () {
$(this).find('img').each(function () {
if ($(this).attr('class') === 'two') {
$(this).fadeIn('slow');
}
if ($(this).attr('class') === 'one') {
$(this).fadeOut('slow');
}
});
});
Any help would be much appreciated.
Thanks for the responses.
I was trying to be too clever and it didn't need it. Is there a way for the the fadein and out to happen simultaneously without the use for a plugin?
Why do the each and not just selected them?
var imgs = $(this).find("img");
imgs.filter(".one").fadeOut('slow');
imgs.filter(".two").fadeIn('slow');
or
var imgs = $(this);
imgs.find(".one").fadeOut('slow');
imgs.find(".two").fadeIn('slow');
Try to do it like this:
$(".one").fadeIn("slow", function() { $(this).fadeOut("slow") });
$(".two").fadeIn("slow", function() { $(this).fadeOut("slow") });
Update:
I misread you question and thought you want both to fade in and out. To make the first one fade in and the second fade out use something like this:
$(".one").fadeIn("slow");
$(".two").fadeOut("slow");
If you have other elements with one and two classes and don't want to affect them, you can type $(".imageHolder .one") and $(".imageHolder .two") instead of $(".one") and $(".two").
If you have multiple imageHolder elements on your page, use find() function as suggested by epascarello or sushanth reddy.
You do not need a .each loop .. Just find the img inside the div and do your operations on it
Try this instead..
$('.square').mouseover(function() {
$(this).find('.two').fadeIn('slow');
$(this).find('.one').fadeOut('slow');
});​
Check FIDDLE
I think this is what you're looking for:
$('.square img')
.mouseover(function () {
$(this).fadeIn('slow');
})
.mouseout(function () {
$(this).fadeOut('slow');
});
I think you will better use jquery.hoverIntent.js. It will create a little delay time when you will move your cursor rapidly over the different images.
an example
$(document).ready(function(){
var config = {
interval: 230,
over: zoomIn,
out: zoomOut
};
$("div#clients_wrap div").hoverIntent(config);
});
zoomIn en zoomOut are functions, you could declare them with an fadein, fadeout respectively. This is just an improvement.
Basically assign a class to the group of images that need to fade in/out on hover in/out respectively
<div class="square">
<div class="imageHolder">
<!--Comment out and uncomment BG image to show transitions on BG images-->
<img class="one fadeeffect" src="image_01.jpg" />
<img class="two fadeeffect" src="image_02.jpg" />
<img class="three" src="image_03.jpg" />
<img class="four" src="image_04.jpg" />
</div>
</div>
javascript:
$('.fadeeffect')..hover(function(){
// write your code here
}

Categories