Making a container grow on hover using jQuery - javascript

I'm trying to make a jQuery function that takes the current height and width of a link then makes it grow by whatever amount of px I set. I don't have much so far and I'm completely lost.
$('.absolute_img_links').hover(function(){
var link_height = $('.absolute_img_links').outerHeight();
var link_width = $('.absolute_img_links').width();
});
I know how to get the current height and width but I don't know how to basically say height of .absolute_img_links = link_height + 10px in jQuery

same functions do the job:
$('.absolute_img_links').hover(function(){
var link_height = $('.absolute_img_links').outerHeight();
$('.absolute_img_links').outerHeight(link_height + 10);
var link_width = $('.absolute_img_links').width();
$('.absolute_img_links').width(link_width + 10);
});

To achieve what you need you can pass a function to the height() and width() functions. In these functions you receive the current value, to which you can just add the 10px as required.
Note that hover() fires twice, once for mouseenter and once for mouseleave. Also, you don't reset the size of the element, so it just gets larger and larger on successive hovering. To fix this, amend your logic so that you attach the event handlers separately instead of one hover() call so you can increase/decrease the size as needed. Try this:
$('.absolute_img_links').on('mouseenter', function(){
$(this)
.height(function(i, height) { return height + 10; })
.width(function(i, width) { return width + 10; });
}).on('mouseleave', function() {
$(this)
.height(function(i, height) { return height - 10; })
.width(function(i, width) { return width - 10; });
});
.absolute_img_links {
position: absolute;
background-color: #C00;
color: #FFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="absolute_img_links">
Hover me!
</div>
Also note that you can implement a pure CSS version of this which has the exact same effect, although simply adds padding to the right and bottom of the element, instead of changing the width/height. Try this:
.absolute_img_links {
position: absolute;
background-color: #C00;
color: #FFF;
}
.absolute_img_links:hover {
padding: 0 10px 10px 0;
}
<div class="absolute_img_links">
Hover me!
</div>
Using the above method you could even keep the text centralised too, by adding a consistent 5px padding around the entire element.

Using height() and width() you can simply add 10 to the values you have found to increase the height/width of the container.
$('.absolute_img_links').hover(function() {
//var link_height = $('.absolute_img_links').outerHeight();
//var link_width = $('.absolute_img_links').width();
//Changed to $(this)
var link_height = $(this).outerHeight();
var link_width = $(this).width();
$(this).height(link_height + 10);
$(this).width(link_width + 10);
});
.absolute_img_links {
width: 300px;
height: 300px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="absolute_img_links"></div>

I know you asked for jQuery but...
This is trivial (and more flexible) in CSS:
.absolute_img_links img { transition: all .2s ease-in-out; }
.absolute_img_links:hover img { transform: scale(1.1); }
<img src="https://placeimg.com/100/100/any" />
<img src="https://placeimg.com/100/100/any" />

Related

jQuery CSS method update on resize?

After struggling to vertically centre a div inside the body element using the "conventional" methods, I've decided to create a small jQuery function that figures out how far from the top an element needs to be to be "centred".
It works like this:
Get container height,
Get child height,
"top" = "(container.height - child.height) / 2"
Set margin top of child to the value of "top".
For example if the body had a width and height of 1000px and this body had a div.inner child that had a width and height of 400px the margin-top of div.inner would be 300px because (1000-400) / 2 = 300.
Here is a diagram to further explain what I mean:
NOTE: X represents the margin-top of the div.inner (as I didn't have enough space for "Margin Top = ").
To my amazement this actually works!!! Here is the test code:
// set the margin top for ".vertical-centre" elements
$(".vertical-centre").each(function() {
// set the margin-top for the child
$(this).css("margin-top", function() {
// NOTE: margin = (container.height - child.height) / 2
var margin = ($(this).parent().height() - $(this).height()) / 2;
// default the margin to zero if it's a negative number
// round the margin down to the nearest whole number
// specify that the margin-top is in pixels
return Math.floor(Math.max(0, margin)) + "px";
});
});
body {
width: 100px;
height: 100px;
margin: 0;
padding: 0;
border: 1px solid black
}
div.inner {
width: 40px;
height: 40px;
background-color: blue
}
.horizontal-centre {
display: block;
margin-left: auto;
margin-right: auto
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inner horizontal-centre vertical-centre"></div>
NOTE: I made the example above smaller so you could see it properly.
Unfortunately though, there is now another problem, when I resize the browser the margin-top of the div.inner element stays the same.
I would like for it to be responsive and update it's margin-top property to the appropriate value when the window has been resized otherwise div.inner will go out of view and the page will look a like this:
You could use https://api.jquery.com/resize/
Create a function of your code
function init_center() {..
Try calling the init_center function from the resize event of window
SNIPPET
function init_center() {
// set the margin top for ".vertical-centre" elements
$(".vertical-centre").each(function() {
// set the margin-top for the child
$(this).css("margin-top", function() {
// NOTE: margin = (container.height - child.height) / 2
var margin = ($(this).parent().height() - $(this).height()) / 2;
// default the margin to zero if it's a negative number
// round the margin down to the nearest whole number
// specify that the margin-top is in pixels
return Math.floor(Math.max(0, margin)) + "px";
});
});
}
$( window ).resize(init_center); // Handle resize of window
init_center(); // Doing it first time
body {
width: 400px;
height: 400px;
margin: 0;
padding: 0;
border: 1px solid black
}
div.inner {
width: 200px;
height: 200px;
background-color: blue
}
.horizontal-centre {
display: block;
margin-left: auto;
margin-right: auto
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inner horizontal-centre vertical-centre"></div>
Wrap you code in a function
function align() {
$(".vertical-centre").each(function() {
// set the margin-top for the child
$(this).css("margin-top", function() {
// NOTE: margin = (container.height - child.height) / 2
var margin = ($(this).parent().height() - $(this).height()) / 2;
// default the margin to zero if it's a negative number
// round the margin down to the nearest whole number
// specify that the margin-top is in pixels
return Math.floor(Math.max(0, margin)) + "px";
});
});
}
And run it on window resize as well
align(); // first run
$(window).on('resize', align); // when window resize

failing on creating a dynamic div to change size on click and back

I created a dynamic page with multiple divs, the divs size is set to 30% each, now I try to make a Jquery that allows you on every time you click to change the div size to 100% and back to 30% on reclicking the div, unfortunate my code is not working:
that is the current jquery I use:
$( document ).ready(function() {
$(".div").click(function() {
if($(this).css("width") == "30%")
$(this).css("width", "100%");
else
$(this).css("width", "30%");
});
});
and that is the css for the div
.div{
min-height:430px;
box-shadow: 1px 1px 7px 0 rgba(0,0,0,0.1);
margin:10px;
float:left;
width: 30%;
min-width: 300px;
transition: width 1s;
}
any solutions guys?
compare it with its parent width:
$( document ).ready(function() {
$(".div").click(function() {
if($(this).outerWidth()==$(this).parent().width())
$(this).css("width", "30%");
else
$(this).css("width", "100%");
});
});
I think this should work
$( document ).ready(function() {
$(".div").click(function() {
var parentWidth = $(this).parent().width()
if($(this).css("width") == .3 * parentWidth)
$(this).css("width", "100%");
else
$(this).css("width", "30%");
});
});
So what is happening here is width: 100% is always equal to its immediate parent
Use class to do this work. When div is clicked add or remove class of element.
$("div").click(function() {
$(this).toggleClass("wide");
});
div {
width: 30%;
height: 50px;
margin: 5px;
float:left;
transition: width 1s;
background: green;
}
.wide {
width: 100% !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
As $(this).css("width") it is always to retrieve a pixels value, then you should calculate the 30% of the container.
var pixels = $('container').css("width");
var pixelsNumber = (parseFloat(pixels) * 30) / 100;
And then compare with it:
if($(this).css("width") == pixelsNumber + "px")
$(this).css("width", "100%");
else
$(this).css("width", "30%");
$(this).css("width") == "30%" will not work.
It will a Boolean.
Also $("#yourElement").width() will always be in integer even though it is specified in % in style properties.
Instead you can calculate the percentage value
var _childWidth = $('#yourElement').width();
var _parentWidth = $('#yourElement').offsetParent().width();
var _percent = (width/parentWidth)*100;
In this case you also need to look the position attribute.
Another simple way of solving your problem
<script>
$('.div').click(function() {
if ($(this).hasClass('hundred')) {
$(this).removeClass('hundred');
} else {
$(this).addClass('hundred');
}
});
add this to your CSS
.hundred {
width: 100%;
}
Simplest way to do that is
Make a class-
.div-100{
width:100%;
}
and then add Jquery
$( document ).ready(function() {
$(".div").click(function() {
$('.div').toggleClass('div-100');
});
});
And here is working demo on code pen

Getting true dimensions of images with jquery on collected dom elements

I am trying to get the dimensions of images on a page for further use with a custom 'lightbox' or sorts. However, when trying both a pure js method, and a jquery method, I get the output undefined on my variables. Why is this? Is it because of jquery load event? I tried both onload and ready.
Basically I need the full dimensions of the image to justify whether it should be loaded in a lightbox with a click event or not.
Update I am now able to get console feedback from the function now, however it's not providing me a dimension of the image.
$('.postbody').find('img').each(function() {
var img = new Image(), width, height;
$(img).load(function() {
width = $(this).width();
height = $(this).height();
console.log('Width: '+width+' Height: '+height);
});
console.log($(this).attr('src'));
img.src = $(this).attr('src');
});
#theater-box {
display: none;
position: fixed;
width: auto;
height: auto;
min-width: 1005px;
max-width: 1428px;
padding: 10px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0,0,0,0.90);
border: 2px solid rgba(255,255,255,0.4);
}
.postbody {
width: 90%;
height: 90%;
background: rgba(100,50,50,0.5);
}
.postbody * img {
width: 100%;
max-width: 1168px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="theater-box"></div>
<div class="postbody">
<div id="someclass"><img src="https://e8zzxa.bl3301.livefilestore.com/storageservice/passport/auth.aspx?sru=https:%2f%2fe8zzxa.bl3301.livefilestore.com%2fy2pDapooeiISgUV7-ugpyADuRULJ_stpkiALbypYJHjNxrhUqcvRsZ6eRk4PiJlClABLOfByjulDSDLOMCEpHhggVkgvM4z5Gdq0Jo-C0e1pCU%2fMajipoorHighlands2.jpg&wa=wsignin1.0" /></div>
</div>
You are setting the variables asynchronously and getting it directly.
In pseudocode it is a bit like this:
Set the function to retrieve the width and height when the images loads
Display the width and height variables (not set yet)
The functions set in step 1 runs and sets the varaibles.
So your code that uses the width and height should be inside the image.load function.
I hope it helps, if you have any further questions dont hesitate to comment :-)
Perhaps you can just put the console.log line as the last line in the $(img).load function.
Try this...
$(img).load = function() {
var $this = $(this);
width = $this.width();
height = $this.height();
}
I'm not exactly sure why the original method (which works in a lot of examples) was not working here. So I found some awesome code by GregL from right here at Stackoverflow.
Essentially, the method loads a new, and hidden image into the body, and then captures the width and height before removing it.
$('.postbody').find('img').each(function() {
var img = $(this), width, height,
hiddenImg = img.clone().css('visibility', 'hidden').removeAttr('height').removeAttr('width').appendTo('body');
width = hiddenImg.height();
height = hiddenImg.width();
hiddenImg.remove();
console.log('Width: '+width+' Height: '+height);
});
Check out the Fiddle

How to center images while keeping them responsive?

Hi please take a look at my site, below is the code snippet in question i have to center my images since ive never had any luck with the css-html methods. The problem is because its set to wait for document.ready() sometimes it will place all my images to the right. Ive tried window.load() but the images center offscreen at smaller window sizes. It was also suggested i try
<div style="
background: url('Assets/image.png') center center no-repeat;
width: 100%;
height: 500px;
">
</div>
but this causes it to lose responsiveness. Ive searched around and i cant find a solution, i just need my images (and the one form) to stay centered and for the images to scale down with the window size.
site: http://bit.ly/11nAQJK
<script type="text/javascript"> //Centering Script
$(document).ready(function () {
updateContainer();
$(window).resize(function() {
updateContainer();
});
});
function updateContainer() {
(function ($) {
$.fn.vAlign = function() {
return this.each(function(i){
var h = $(this).height();
var oh = $(this).outerHeight();
var mt = (h + (oh - h)) / 2;
$(this).css("margin-top", "-" + mt + "px");
$(this).css("top", "50%");
$(this).css("position", "absolute");
});
};
})(jQuery);
(function ($) {
$.fn.hAlign = function() {
return this.each(function(i){
var w = $(this).width();
var ow = $(this).outerWidth();
var ml = (w + (ow - w)) / 2;
$(this).css("margin-left", "-" + ml + "px");
$(this).css("left", "50%");
$(this).css("position", "absolute");
});
};
})(jQuery);
Remove that whole script. Place this in your CSS.
img{
display: block;
margin: 0 auto;
}
just do
<style>
a{
display:block;
text-align:center;
}
</style>
<a href="Assets/OrderSheet.xls">
<img src="Assets/OrderSheet.png" class="image">
</a>
no need for repositioning
fiddle
No need for js, CSS alone is fine. Set your image to display block, set a width and Max width plus margin auto.
img {
display: block;
width: 300px;
max-width: 100%;
margin: 0 auto;
}
If you won't accept the method suggested by others, I would suggest using em's. Best to use them everywhere, but you could just apply them to your images.
Then use media queries to scale up/down all elements with values specified in em's, by changing the base font-size for different screen sizes.
center a responsive sized element
/* element/id/class */
/* margin is 100 - width / 2 */
img {
width:34%;
margin: 0 33%;
}

Animation for the automatic height change when content is resized with javascript

I want to control the automatic height change of the container when I add something that changes the lenght of the content. Right now, if I apply a innerHTML change on the content, the height is changed accordingly. I want to apply a transition to that height change. How can I do that? ( I can also use jQuery )
Record the height before changing the content, change the content, record the height after, set the height to the former height, and animate to the latter height. When the animation has completed, set the height to be automatic again. You can do this using height and animate.
Try it on JSFiddle.
var texts = [
"This is just some sample text that's being used to demonstrate animating the height when content changes.",
"Shorter."
];
var div = $('div').click(changeContent);
function changeContent() {
var oldHeight = div.height();
texts.push(div.text());
div.text(texts.shift());
var newHeight = div.height();
div.height(oldHeight);
div.animate({height: newHeight}, 'fast', function() {
div.height('auto');
});
}
div {
width: 150px;
background: lightgray;
overflow-y: hidden;
}
<div>This is some example content.</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="containter" style="overflow:hidden">
<div>
Content.....
</div>
</div>
//add something...
$('#container').animate({height:$('#container').content().outerHeight()});
or:
$('#container').animate({height:$('#container').children().first().outerHeight()});
and when adding append to the div inside the containter:
$('#container').children().first().append(somethingNew);
Based on icktoofay's answer.
I make the button disabled while changing the height and add a fading effect. This solution is useful for updating of the products filter and so on.
Also I check the box-sizing property. If it's box-sizing then I get newHeight by .outerHeigth() instead of .height() to prevent the height fluctuation when new content has the same height. You can check this situation, for example by setting the random variable to value 5. The reason is that
.height() will always return the content height, regardless of the value of the CSS box-sizing property.
CodePen
$('#button').click(function() {
var $button = $(this),
buttonOriginalText = $button.html();
$button.prop('disabled', true).html('Updating...');
$('#content').animate({
opacity: 0
}, 'fast', function() {
var newHeight,
$content = $(this),
oldHeight = $content.height();
$content.html(getRandomContent());
newHeight = ('border-box' === $content.css('box-sizing') ? $content.outerHeight() : $content.height());
$content.height(oldHeight).animate({
height: newHeight,
opacity: 1
}, 'slow', function() {
$content.height('auto');
$button.prop('disabled', false).html(buttonOriginalText);
});
});
});
function getRandomContent() {
var random = 1 + Math.round(Math.random() * 11), // 1..12
paragraph = '<p>Paragraph</p>';
return paragraph.repeat(random);
}
* {
box-sizing: border-box; /* comment out to test "content-box" */
font: 16px Helvetica, 'sans-serif';
}
.content {
counter-reset: content;
padding: 6px 18px;
}
.content p {
counter-increment: content;
}
.content p:after {
content: ' ' counter(content) '.';
}
.content-box {
border: 2px solid red;
margin-top: 24px;
max-width: 220px;
}
<button id="button" class="button">Update the content</button>
<div class="content-box">
<div id="content" class="content">Animatie the automatic height when content is resized.</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

Categories