I have a div containing a label and 4 divs. I want some css and jQuery to affect the 4 child divs, but not the label, and so I wrote the following:
HTML:
<div class="score row-fluid">
<label class="span8">Text...</label>
<div class="span1"><img></div>
<div class="span1"><img></div>
<div class="span1"><img></div>
<div class="span1"><img></div>
</div>
CSS
.score > div {
cursor:pointer;
}
jQuery
$('> div', '.score').on('mouseenter', function() {
if($(this).not('.score-selected')) {
var $img = $(this).children('img');
var point = $img.attr('src').lastIndexOf('.');
var src = $img.attr('src').substring(0,point);
var newSrc = src + "-hover" + $img.attr('src').substring(point);
$img.attr('src', newSrc);
}
})
.on('mouseleave', function() {
if($(this).not('.score-selected')) {
var $img = $(this).children('img');
var point = $img.attr('src').lastIndexOf('.');
var point2 = $img.attr('src').lastIndexOf('-hover');
var src = $img.attr('src').substring(0,point2);
var newSrc = src + $img.attr('src').substring(point);
$img.attr('src', newSrc);
}
});
However the label has a pointer cursor, and it fires the mouseenter/leave JavaScript.
I've created a fiddle here, and interestingly it's not firing the JavaScript on the fiddle, but it is still being affected by the css.
Does anyone know why this label is being treated as if it's a div?
Bootstrap is giving label the pointer, and your mouse events are being called on .score as well as > div. When you hover over the label, you are also hovering over .score
EDIT: I changed the logging on your JS fiddle, here http://jsfiddle.net/sEa5W/1/
The mouse enter isn;t getting fired from the label, but the mouse exit is being called when you hover over to the mouse label from one of the DIVs because you are exiting the DIV.
perhaps it is an idea (if you use html5) to use <img data-large="path-to-large-image" and use that in your jQuery selection.
<div class="score row-fluid">
<label class="span8">Text...</label>
<div class="span1"><img src="thumbnail1.jpg" data-large="fullsize1.jpg" alt="img1" /></div>
<div class="span1"><img src="thumbnail2.jpg" data-large="fullsize2.jpg" alt="img2"></div>
<div class="span1"><img src="thumbnail3.jpg" data-large="fullsize3.jpg" alt="img3"></div>
<div class="span1"><img src="thumbnail4.jpg" data-large="fullsize4.jpg" alt="img4"></div>
</div>
and the jQuery:
$('div.score>div.span1').on('mouseenter', function() {
if($(this).not('.score-selected')) {
var $img = $(this).children('img');
$img.attr('src', $img.attr('data-large'));
}
})
.on('mouseleave', function() {
if($(this).not('.score-selected')) {
var $img = $(this).children('img');
$img.attr('src', $img.attr('data-large'));
}
});
edit lol, just noticed I used large twice, but this can also be done with small or something. just data-anything. It was just a way to show you that you do not have to manipulate strings, but that you can use html5 data attributes.
Related
I have drag-and-drop items, intended to be dragged from one div and dropped into another div. I capture the original position of each item in hidden fields when they are created.
I want to get the items to go back to the original div and location on dblclick, but they always relocate inside the drop target div.
Any ideas?
<div id="cardPiles">
<div id="D1" class="draggable" ondblclick="rev(this)">1</div>
<div id="D2" class="draggable" ondblclick="rev(this)">2</div>
<div id="D3" class="draggable" ondblclick="rev(this)">3</div>
<div id="D4" class="draggable" ondblclick="rev(this)">4</div>
<div id="D5" class="draggable" ondblclick="rev(this)">5</div>
<div id="D6" class="draggable" ondblclick="rev(this)">6</div>
</div>
function rev(me) {
var b = $(me).text();
var h = $('#H' + b).text();
var s = h.split(',');
var top = s[0];
var left =s[1];
$(me).parent().css({ position: 'relative' }); //tried absolute also
$(me).css({top:top,left:left,position:'absolute' });
}
Here is a possible answer. If it does not fit your use case, edit your post with more details.
Working Example: https://jsfiddle.net/Twisty/u1rd9dpg/6/
HTML
<div id="cardPiles">
<div id="D1" class="draggable ui-widget-content" data-origin="">1</div>
<div id="D2" class="draggable ui-widget-content" data-origin="">2</div>
<div id="D3" class="draggable ui-widget-content" data-origin="">3</div>
<div id="D4" class="draggable ui-widget-content" data-origin="">4</div>
<div id="D5" class="draggable ui-widget-content" data-origin="">5</div>
<div id="D6" class="draggable ui-widget-content" data-origin="">6</div>
</div>
<div id="cardDrop">
</div>
JQuery
function rev(me) {
console.log("DoubleClick Detected.");
var pos = me.data("origin");
console.log("Returning to: ", pos);
var $o = me.clone();
$o.draggable({
cursor: "move",
start: log
});
me.remove();
if ($("#cardPiles div").length == 0) {
$("#cardPiles").append($o);
return true;
}
$("#cardPiles .draggable").each(function(k, v) {
var txt = parseInt($(v).text());
if ($o.data("order") < txt) {
$(v).before($o);
return false;
} else {
$("#cardPiles").append($o);
}
});
}
function log(e, ui) {
var pos = ui.offset;
var $ob = $("#" + ui.helper.attr("id"));
pos.order = parseInt(ui.helper.text());
$ob.attr("data-top", pos.top);
$ob.attr("data-left", pos.left);
$ob.attr("data-order", pos.order);
$ob.attr("data-origin", [pos.top, pos.left, pos.order].join(","));
console.log("DragStart Position: ", pos);
console.log("Logged: " + [$ob.data("top"), $ob.data("left"), $ob.data("order")].join(","));
}
$(function() {
$(".draggable").draggable({
cursor: "move",
start: log
});
$("#cardDrop").on("dblclick", ".dropped", function() {
console.log("Origin found: ", $(this).data("origin"), $(this).data("top"));
rev($(this));
});
$("#cardDrop").droppable({
accept: "#cardPiles div",
activeClass: "ui-state-highlight",
drop: function(e, ui) {
var $drop = ui.draggable.clone();
console.log("Dropped. Origin: ", $drop.data("origin"));
$drop.removeAttr("style");
$drop.addClass("dropped");
$(this).append($drop);
ui.draggable.remove();
var c = $("#cardDrop div").length;
}
}).sortable({
revert: true
});
});
I'm not sure if you need to do this in CSS or not, but I went based on the order and let the CSS just define how they appear in the list.
When the drag starts, I log the origin details to various data attributes. This allows them to be retrieved later when there is an interaction with just that element.
When drop happens, I clone the original and then append the clone. Do not have to do this, yet for me, it helps me identify whats happening. Since it's no longer draggable, you could remove the class, but I just added dropped to be able to more easily catch the Double Click event.
When dblclick fires on our object, I clone it again, and re-append it back. Make it .draggable() again too. I hunt for the next item's number and fit it in underneath.
If the text within is not easy to order like that, I would add an order attribute or populate the data-order attribute. You can do this when it's dragged or read it from the ID... not sure what might work best for you.
You can do this over and over and drag all of them out of #cardPile if you like.
I have a few images of superheroes. These are in divs along with much larger images of astronomical objects. These larger images take a while to load. I want the astronomical images to replace the superhero images after they've loaded.
Here's what I have so far: https://jsfiddle.net/vmpfc1/5typ7pnp/1/
HTML:
<body>
<div class="image-wrapper">
<div class="pix"style="background: url('http://baltimorepostexaminer.com/wp-content/uploads/2012/07/spider-man2_pole_4681.jpg'); height:200px;width:200px;">
</div>
<div class="true-image" style="background: url('http://m1.i.pbase.com/o9/27/876727/1/151851961.JlvdQ9xW.GreatCarinaKeyholeandRedHoodNebulae3454x2566pixelsimproved3.jpg')"></div>
</div>
<div class="image-wrapper">
<div class="pix"style="background: url('https://upload.wikimedia.org/wikipedia/en/7/75/Comic_Art_-_Batman_by_Jim_Lee_%282002%29.png'); height:200px;width:200px;">
</div>
<div class="true-image" style="background:url(' https://www.nasa.gov/sites/default/files/706439main_20121113_m6triptych_0.jpg')"></div>
</div>
</body>
js:
setTimeout(function () {
$('.true-image').attr('style').on('load', function () {
$('.pix')({
'background-image': 'url(' + $(this).attr('src') + ')'
});
});
}, 0);
css:
.true-image {
display : none;
}
I am a javascript newbie -- is there a decent way to make the larger space images replace the superhero placeholders?
Is there an easier way to do this in HTML5?
Edited Answer to reflect changes:
<div style="background-image: url('https://i.imgur.com/sOcRl3M.jpg'); height:400px;width:400px" rel="https://i.imgur.com/xr7CRQo.jpg">
</div>
<div style="background-image: url('https://i.imgur.com/1m0NwgN.png'); height:400px;width:400px" rel="https://i.imgur.com/nlFPkc4.jpg">
</div>
Then you can have jQuery to loop through all images which has a rel attribute. 2 or 2,000 images, it does not matter.
$('div[rel]').each(function() {
var rel = $(this).attr('rel');
var self = $(this);
var img = new Image();
$(img).load(rel, '', function() {
self.css('background-image', 'url('+rel+')');
});
});
You can see it working here: https://jsfiddle.net/83zLumuk/4/
I have a div as :
<div id="div1" width="100px" height="100px">
</div>
Now within this div I want to place 20 elements, but dynamically it can grow upto 50 elements(images) also.
I am using the following code to append these elements in a div,
var i = document.createElement("img");
var d= document.getElementById("div1");
d.appendchild(i);
Now, the issue is ,as the number of elements increase the elements are going out of div ,and if I use the max-width and max-height on images, the result doesnt change:
i.setAttribute('max-width', '100%');
i.setAttribute('max-height', '100%');
Is there anything which I am missing?
Edit:
The images need to shrink as the div size is fixed
If the width is fixed and the height is dynamic. The image will shrink and they will get stacked. Check my fiddle here
img {
width:100%;
display:inline-block;
}
<div style="width:100px;border: 1px solid black;">
<img src="http://www.brightlinkprep.com/wp-content/uploads/2014/04/sample.jpg" />
<img src="http://www.brightlinkprep.com/wp-content/uploads/2014/04/sample.jpg" />
<img src="http://www.brightlinkprep.com/wp-content/uploads/2014/04/sample.jpg" />
</div>
Cant think of a nice way to do it with percentages,
var imags = document.getElementsByTagName('img');
var count = imags.length;
for (var index= 0,l= count;index<l;index++){
imags[index].setAttribute('height', (100/count)+'%');;
}
its not pretty but should work.
i smushed something together from all the answers that fits your needs (if i understand you correctly)
https://jsfiddle.net/b30d88g6/3/
the div has fixed width/height and the images wont get out of the div
function add_img() {
var i = document.createElement("img");
i.src= "https://jsfiddle.net/img/logo.png";
var d= document.getElementById("div1");
d.appendChild(i);
var imags = document.getElementsByTagName('img');
var count = imags.length;
for (var index=0, l=count;index<l;index++){
imags[index].setAttribute('height', (100/count)+'%');;
}
}
I have some divs with same class. Inside this divs i added another div to put an ad.
Now i am trying to hide the ad div if the width of the div that holds my ad div is equal to 366px;
I tried the code bellow but it hides only my first ad div..
Example:
<div class="masterdiv">
<div id="myaddiv"></div>
</div>
<div class="masterdiv">
<div id="myaddiv"></div>
</div>
<div class="masterdiv">
<div id="myaddiv"></div>
</div>
and my jquery code is:
var adwidth = $(".masterdiv").width();
if (adwidth == 366){
$('#myaddiv').hide();
}
Thank you!
Because var adwidth = $(".masterdiv").width(); only returns the first value. The answer is in your title, you need to use each. Another issue is ids are SINGULAR, so you need to use a class
Using each:
$(".masterdiv").each( function() {
var elem = $(this);
var width = elem.width();
if (width == 366){
elem.find('.myaddiv').hide(); //use a class since only one element can have an id
}
});
Using filter:
$(".masterdiv").filter( function() {
return ($(this).width() == 366);
}).find('.myaddiv').hide();
The updated HTML:
<div class="masterdiv">
<div class="myaddiv"></div>
</div>
you should not use duplicate ids.use:
$('div .masterdiv').each(function(){
if($(this).width()==366){
$(this).find('div').hide();
}});
Try:
$('.masterdiv').each(function(){
if($(this).width()==386){
$(this).hide();
}
});
This is only doing the first div because you are using id's instead of classes. Since there can only be one id per page javascript stops after matching the first one. change to classes and you should be fine.
you are using same id's for different divs
Instead of id, give class name
<div class="masterdiv">
<div class="myaddiv">
</div>
</div>
<div class="masterdiv">
<div class="myaddiv">
</div>
</div>
<div class="masterdiv">
<div class="myaddiv">
</div>
</div>
$(document).ready(function () {
var adwidth = $(".masterdiv");
for (i = 0; i < adwidth.length; i++) {
if ($(adwidth[0]).attr("width") == 366) {
$(this).find('.myaddiv').hide()
}
}
});
$(".masterdiv").each(function(){
var current = $(this);
if(current.width() == 366) {
current.hide();
}
});
You have to change in this way:
$('#myaddiv', '.masterdiv').each(function() {
var width = $(this).width();
(width > 366) ? $(this).hide() : 0;
});
You can try on this live DEMO
i have a single div 100px X 300px. What's the easiest way in JavaScript so when I hover over the div i show an image and then when i leave the div the image disappears.
for starters i thought the following would get me started but i can't seem to remove the image properly
<script type="text/javascript">
function MouseOver_Event(elementId) {
var imgToCreate = document.createElement('img');
imgToCreate.setAttribute('id', 'imgHandle');
imgToCreate.setAttribute('src', elementId + '.png');
imgToCreate.setAttribute('onmouseout', 'MouseOut_Event('+elementId+')');
var targetDiv = document.getElementById(elementId);
targetDiv.appendChild(imgToCreate);
targetDiv.removeAttribute('onmouseover', 'MouseOver_Event');
}
function MouseOut_Event(elementId) {
var imgToRemove = document.getElementById('imgHandle');
var targetDiv = imgToRemove.parentNode();
if (imgToRemove != null)
targetDiv.removeChild(imgToRemove);
targetDiv.setAttribute('onmouseover', 'MouseOut_Event(' + elementId + ')');
}
</script>
</head>
<body>
<div id="div1" onmouseover="MouseOver_Event(this.id)"></div>
<div id="div2" onmouseover="MouseOver_Event(this.id)"></div>
<div id="div3" onmouseover="MouseOver_Event(this.id)"><img src="Div3.png" alt="test" onmouseout="MouseOut_Event(parentNode's id or something)" /></div>
</body>
You're attaching your MouseOut_Event to onmouseover instead of onmouseout. But you probably don't need to be messing with dynamic event creation anyway; just add onmouseout="MouseOut_Event(this.id)" to the three divs and that should do it.
Why don't you use CSS instead ?
For example:
#div1{background:none;}
#div1:hover{background:url('src/div1.png') no-repeat;}