How to add images one on another image using javascript - javascript

I have small requirement: I need add image over(up) the another image through javascript. Please give me the suggestion!
function sampleImage()
{
document.getElementById('img1').innerHTML='<img src="C:\Users\rajasekhark\Desktop\assets\images\Cock.png" />';
}

You need to enclose the two images in a <div> and then use the following CSS attributes:
div {
position: relative;
}
​#img2 {
position: absolute;
top: 100px;
left: 100px;
}
See http://jsfiddle.net/C8hh4/
The second image must be a sibling of the first, it cannot be a descendent because that's not legal HTML. The <div> needs to have relative position otherwise #img2's absolute position will be calculated relative to the closest ancestor that doesn't have the default static position.
The value for top should be half of the difference between the outer image's height and the inner image's height, and likewise for the left / width.
If your content is static, calculate those values by hand. If it's dynamic, use JS to set the style:
var img1 = $('#img1')[0];
var img2 = $('#img2')[0];
var top = 0.5 * (img1.height - img2.height);
var left = 0.5 * (img1.width - img2.width);
$(img2).css({top: top, left: left});

You could use relative positioning.
Stack the images on top of each other and set position:relative;top:VALUE;
Value should be -HalfHeightOfBackgroundImage-HalfHeightOfForegroundImage.
Another approach whould be wrapping the foreground image in a div and setting the the background image as the background-image.

Why javascript? Of course, you could use a canvas and paint them over each other, but I would recommend simple CSS:
<img
style="padding: 20px 7px, background: url('/some/frame.png')"
src="/cock.jpg"
width="50px" height="40px"
/>
You might use a class for that, the inline style is just shorter.

You should do (I saw jquery tag):
$("#img1 img").first().prop("src", "C:\Users\rajasekhark\Desktop\assets\images\Cock.png");
And an advice: DO NOT use full path to your local disk ...

The jQuery option would be
$("#img1").prop("src","blahblah.jpg");
Although I don't really understand your question.
If you mean that you need to change the image on hover then perhaps this will help...
$("#img1").hover(
function () {
$(this).prop("src","newImage.jpg");
},
function () {
$(this).prop("src","originalImage.jpg");
});
EDIT:
OK...
What you need is a div with the green flashcard as the background image. And place the cock image in that div but set to display:none;
Then on hover just show the image of the cock.
$("#containerDiv").hover(
function () {
$(this).find("img").show();
},
function () {
$(this).find("img").hide();
});

Related

advice on how to best to reveal additional content based on the contents height

I have a #banner that holds content, basically what i want to do is show a certain amount of the content and then have a more button that will show the rest of the content if clicked. This in turn will also animate the height of #banner, I have set the #banner height at 300px but want to find the height of the content #inner and animate this accordingly. At the moment I have the following version but reckon Im using a lot of #ids / to achieve the effect, can anyone advise how I can make this better?
Fiddle here: http://jsfiddle.net/43gTt/1/
Thanks
Kyle
I suggest you compute the height of the inner div and use that to animate.
var $tmpInner = inner.clone().appendTo('body');
var divHeight = $tmpInner.outerHeight();
$tmpInner.remove();
Below will compute the height of the innerDiv based on the content of the div.
Also, updated the css style for the banner to overflow:hidden so that you don't need separate animate for the banner.
DEMO
CSS:
#banner{background:#dedede;overflow: hidden; }
#outer{margin:0 auto;width:200px;}
#middle{height:200px;overflow:hidden}
#inner{width:200px;margin:0 auto;}
.entry{display:none;}
JS:
$(document).ready(function() {
var outer = $('#outer'),
middle = $('#middle'),
inner = $('#inner'),
/*innerH = inner.height(),*/
banner = $('#banner'),
more = $('#more');
var $tmpInner = inner.clone().appendTo('body');
var divHeight = $tmpInner.outerHeight();
$tmpInner.remove();
// animate banner and #middle to reveal additional content
more.on('click', function(e) {
middle.animate({
height: divHeight
}, 300);
/*banner.animate({
height: innerH
}, 300);*/
});
});
Note: I am not sure why you need that many wrappers div, but I presume that would be part of your HTML. Also I will leave the code cleanup to you.

Insert a logo next to any DOM element

I'm developing a Firefox extension which amends the contents of a loaded webpage. First I select all the elements of which the "src" or "href" attributes match my regex (this part of the code works).
Then, I would like to place a little image at the top right corner of the found element's parent using the following code:
/* create and add attributes to image */
var img = window.content.document.createElement("img");
var b = window.content.document.createAttribute("src");
b.nodeValue = "chrome://plugin/content/agent.png";
img.setAttributeNode(b);
img.addEventListener("click", function(){ alert("ds"); });
img.style.display = "block";
img.style.border = "3px solid red";
img.style.position = "relative";
img.style.top = "-10px";
img.style.right = "-10px";
img.style.left = "20px";
// ... the code to return the element...
//now insert the image
$jq(img).appendTo(element.parentNode);
The current result is that either the image is shown just at the bottom of the element's parent or not shown at all.
If you look at this: http://jsfiddle.net/yzwh5/64/ - I would like my button to work in a similar manner to that red cross.
You must "play" with the element's CSS positioning, in fact it doesn't matter where do you insert the images, but where you do position them.
Maybe you would like to take a look at "next-to", a jQuery plugin that automates the calculations to position an element next to another element
For example:
<script type="text/javascript">
$('.PlaceThisDiv').nextTo($('.ThisOtherDiv'), {position:'right', shareBorder:'top'});
</script>
As you can see in this Fiddle i have prepared (contains the plugin itself)
http://jsfiddle.net/PvcNr/
you will get you something like this:
More info: https://code.google.com/p/next-to/
Hope it helps
Try CSS code like this:
.my-ext-overlay:after {
content:url(smiley.gif);
position: absolute;
margin-left: -16px; margin-top: -16px;
}
and then adding the ".my-ext-overlay" class name to each element you find.
See example
Firstly, CSS floats are called cssFloat (or htmlFloat in some browsers) because float is a reserved word. Second, there is no such float value as block.
Third, you missed an x in -10px for the right property.
Fourth, setting both relative left and right positions can lead to unexpected behaviour.
Fifth, you shouldn't use createAttribute, since attribute nodes aren't reliable in all browsers. Instead, use setAttribute on the element.
Sixth, if this did work it would mess up page layout around the element you're searching for, so you would be better off with position: absolute so it doesn't affect the flow. If you do this, however, you should use margin-left instead of left (same for other directions), to shift the element around.
I think that should at least get the thing close to working...

How can I move a background image pattern around?

I've looked around for this but I couldn't find an answer, and I don't have a clue how I would do it. What I am looking for is a JavaScript or jQuery script that will "move" a background image to the right in a div container, so that the pattern will have an "animated" effect.
How would it be possible to do this? I apologize if I have not explained the question in enough detail.
You can use the CSS background-position property to set the position of the background.
Here's a live example that moves the background one pixel to the right every quarter second, resetting when it reaches 100 pixels.
HTML:
<div id="theDiv">This is the div</div>
CSS:
#theDiv {
background-image: url(http://www.gravatar.com/avatar/7b13c109d50df67d5f7d0b1d901d7fb7?s=32&d=identicon&r=PG);
background-repeat: no-repeat;
}
JavaScript:
jQuery(function($) {
var pos = 0;
move();
function move() {
++pos;
if (pos > 100) {
pos = 0;
}
$("#theDiv").css("background-position", pos + "px");
setTimeout(move, 250);
}
});
You cannot use jQuery.animate on a background position, because:
All animated properties should be animated to a single numeric value.
And background-position is not a single numeric value property.
Thus, your best bet is to not use a background image in this case directly. You could re-do your layout so that the image is actually an absolutely positioned <div> (the size of your background image) within another fixed-size <div> container (position: relative; overflow: hidden;). And then to make it "move" -- animate CSS left property on your absolutely positioned <div>.

Change a div background with jQuery

I need to change my background div with some other images.
I want that first, myDiv load the first background image on css style, and then within 2/3 seconds of delay add a fade effect change the background image.
If it's possible, I need to do this with jQuery.
You cannot do fade or any other transitions directly on the background image. You can however add another div with second image as its background and fadeOut() the original one.
Does this do what you you want?
http://jqueryfordesigners.com/image-loading/
EDIT: A bit more Googling - this sounds like what you are trying to do...
http://www.magneticwebworks.com/jquery-rotating-page-background/
Edit: another go - THis? http://css-tricks.com/forums/discussion/9621/solved-is-it-possible-to-add-jquery-cycle-to-background-imagess/p1
this is not fade effect but you can delay and change background image like this.
function changebackground(){
$('#divID').css("background-image", "url(/myimage.jpg)");
}
setTimeout(function() { changebackground();}, 3000);
this might be good workaround
http://jquery.malsup.com/cycle/
after you position on top divs with cycle it can be your background - cycle.js give's you lot of options.
if you want only rotate image's in bacground you must first preload that image and second you must put it in other div so that both divs can animate.
There is no support for this, even if you add all the functionality of jQuery UI.
You could append a temporary image, absolutely positioned inside the div for which u want to change background. Let the image fade in, and once it's fully opaque, swap background image for the div. This will be problematic if you have a repeated background, however.
var im1 = 'picture1.png';
var im2 = 'picture2.png';
$('#divID').css({'background-image': 'url("'+im1+'")', 'position': 'relative'});
$('#divID').on('click', function() {
var img = $('<img />', {
src: im2,
}).css({
position: 'absolute',
top: 0,
left: 0
}).hide();
$(this).append(img);
img.fadeIn('slow', function() {
$(this).parent().css('background-image', 'url("'+im2+'")');
$(this).remove();
});
});
Of course, you should move the CSS I included in my script to a .css file, and use a class instead, for more readable code.

Find the "potential" width of a hidden element

I'm currently extending the lavalamp plugin to work on dropdown menus but I've encountered a small problem. I need to know the offsetWidth of an element that is hidden. Now clearly this question makes no sense, rather what I'm looking for is the offsetWidth of the element were it not hidden.
Is the solution to show it, grab the width, then hide again? There must be a better way...
The width of an element that has CSS visibility: hidden is measurable. It's only when it's display: none that it's not rendered at all. So if it's certain the elements are going to be absolutely-positioned (so they don't cause a layout change when displayed), simply use css('visibility', 'hidden') to hide your element instead of hide() and you should be OK measuring the width.
Otherwise, yes, show-measure-hide does work.
The only thing I can think of is to show it (or a clone of it) to allow retrieval of the offsetWidth.
For this measurement step, just make its position absolute and its x or y value a big negative, so it will render but not be visible to the user.
You can use the following function to get the outer width of an element that is inside a hidden container.
$.fn.getHiddenOffsetWidth = function () {
// save a reference to a cloned element that can be measured
var $hiddenElement = $(this).clone().appendTo('body');
// calculate the width of the clone
var width = $hiddenElement.outerWidth();
// remove the clone from the DOM
$hiddenElement.remove();
return width;
};
You can change .outerWidth() to .offsetWidth() for your situation.
The function first clones the element, copying it to a place where it will be visible. It then retrieves the offset width and finally removes the clone. The following snippet illustrates a situation where this function would be perfect:
<style>
.container-inner {
display: none;
}
.measure-me {
width: 120px;
}
</style>
<div class="container-outer">
<div class="container-inner">
<div class="measure-me"></div>
</div>
</div>
Please be aware that if there is CSS applied to the element that changes the width of the element that won't be applied if it's a direct descendant of body, then this method won't work. So something like this will mean that the function doesn't work:
.container-outer .measure-me {
width: 100px;
}
You'll either need to:
change the specificity of the CSS selector ie. .measure-me { width: 100px; }
change the appendTo() to add the clone to a place where your CSS will also be applied to the clone. Ensure that where ever you do put it, that the element will be visible: .appendTo('.container-outer')
Again, this function assumes that the element is only hidden because it's inside a hidden container. If the element itself is display:none, you can simply add some code to make the clone visible before you retrieve it's offset width. Something like this:
$.fn.getHiddenOffsetWidth = function () {
var hiddenElement $(this)
width = 0;
// make the element measurable
hiddenElement.show();
// calculate the width of the element
width = hiddenElement.outerWidth();
// hide the element again
hiddenElement.hide();
return width;
}
This would work in a situation like this:
<style>
.measure-me {
display: none;
width: 120px;
}
</style>
<div class="container">
<div class="measure-me"></div>
</div>
Two options:
position the element outside the viewport (ex: left:-10000px)
use visibility: hidden or opacity: 0 instead of hide().
Either way will work as hiding the element but still being able to get the computed width. Be careful with Safari on thi, it's awfully fast and sometimes too fast...
Actual jQuery plugin!
Usage:
console.log('width without actual: ' + $('#hidden').width());
console.log('width with actual: ' + $('#hidden').actual('width'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.actual/1.0.19/jquery.actual.min.js"></script>
<div style="width: 100px; display: none;">
<div id="hidden"></div>
</div>
If you know the element to be the full width of a parent element another approach is to create a recursive method:
es5:
var getWidth;
getWidth = function($el){
return $el.offsetWidth || getWidth($el.parentElement);
}
var width = getWidth(document.getElementById('the-element'));
es6:
let getWidth
getWidth = ($el) => $el.offsetWidth || getWidth($el.parentElement)
const width = getWidth(document.getElementById('the-element'))
What I did was ;
by the time hiding that element, stored its width in its dataset.
It only will work for you if you can hide programmatically.
ie.
When Hiding ;
var elem = $("selectorOfElement");
elem.dataset.orgWidth = elem.clientWidth;
Later when getting ;
var elem = $("selectorOfElement");
var originalWidthWas = elem.dataset.orgWidth;
thats because its hidden via display: none; What ive done in the past is to make a "reciever" div which i use absolute positioning on to get it off the page. Then i load the new element into that, grab the dimensions and then remove it when im done - then remove the reciever when im done.
Another thing you can do is to not use hide(); but to instead set visibility: hidden; display: ; However this means the blank area will be rendered wherever the node is attached.
var $hiddenElement = $('#id_of_your_item').clone().css({ left: -10000, top: -10000, position: 'absolute', display: 'inline', visibility: 'visible' }).appendTo('body');
var width = parseInt($hiddenElement.outerWidth());
$hiddenElement.remove();
I try to find working function for hidden element but I realize that CSS is much complex than everyone think. There are a lot of new layout techniques in CSS3 that might not work for all previous answers like flexible box, grid, column or even element inside complex parent element.
flexibox example
I think the only sustainable & simple solution is real-time rendering. At that time, browser should give you that correct element size.
Sadly, JavaScript does not provide any direct event to notify when element is showed or hidden. However, I create some function based on DOM Attribute Modified API that will execute callback function when visibility of element is changed.
$('[selector]').onVisibleChanged(function(e, isVisible)
{
var realWidth = $('[selector]').width();
var realHeight = $('[selector]').height();
// render or adjust something
});
For more information, Please visit at my project GitHub.
https://github.com/Soul-Master/visible.event.js
demo: http://jsbin.com/ETiGIre/7
Sorry I am late to this conversation. I am surprised no one has mentioned getComputedStyle. (Note this only works if the CSS sets a width value)
Grab the element:
let yourEle = document.getElementById('this-ele-id');
and use the function:
getComputedStyle(yourEle).width
This returns a string so you will have to remove the numbers from the string.
This works even when the element's display style is set to none.
Other articles to read about this includes here at zellwk.com

Categories

Resources