I have created a responsive site and then used some JS code to create captions on the images which works fine but when I re-size the browser. The images don't scale like they should and I believe its due to being given a height value in the JS. How do I remove this value and make the caption work?
$(window).load(function(){
// For each instance of p.caption
$("p.caption").each(function(){
$(this)
// Add the following CSS properties and values
.css({
// Height equal to the height of the image
"height" : $(this).children("img").height() + "px",
// Width equal to the width of the image
"width" : $(this).children("img").width() + "px"
})
// Select the child "span" of this p.caption
// Add the following CSS properties and values
.children("span").css(
// Width equal to p.caption
// But subtract 20px to callibrate for the padding
"width", $(this).width() - 20 + "px")
// find the <big> tag if it exists
// And then add the following div to break the line
.find("big").after('<div class="clear"></div>');
// When you hover over p.caption
$("p.caption").hover(function(){
// Fade in the child "span"
$(this).children("span").stop().fadeTo(400, 1);
}, function(){
// Once you mouse off, fade it out
$(this).children("span").stop().delay(600).fadeOut(400);
});
// End $(this)
});
});
I think you should try window.resize.
$(window).resize(function() {
$("p.caption").each(function() {
var item = $(this);
var big = item.find("big");
item.css({
"height" : item.children("img").height() + "px",
"width" : item.children("img").width() + "px"
}).children("span").css("width", item.width() - 20 + "px");
});
});
I refactored your code and created a fiddle:
http://jsfiddle.net/VinnyFonseca/6Kv9U/1/
jQuery.resize() will solve this for you http://api.jquery.com/resize/
You just have to store that procedural code to be re-executable (function) and then retrigger it based on relative (parent) DOM dimensions.
'use strict';
removeHeight(){
// That code here
}
$(document).ready(function(){
// Initial removal
removeHeight();
// Removal when resizing
$(window).resize(function() { removeHeight() });
});
Related
I have a function that resizes divs depending on how high (in pixels) other divs with the same class are:
<script type="text/javascript">
function resizeTheDivs(tag){
// first get the tags to adjust
var $tags = $('.' + tag);
var $new_height = 0;
// find out which one is largest
$('.' + tag).each(function(){
$(this).height() > $new_height ? $new_height = $(this).height() : null;
});
// make all others that height
$tags.height($new_height);
// I console.log($new_height) here sometimes
}
// resize divs on document load
$(document).ready(function(){
resizeTheDivs('the-class');
});
// resize divs on window resize
$(window).resize(function () {
resizeTheDivs('the-class');
});
</script>
The divs resize correctly on page load, but when console.log($new_height) fires from the window resize function, the $new_height is not changed.
Context: There are 3 divs (floated left, so next to each other with 33% width) that contain text in p tags. So when I resize the browser width, the text gets 'longer', but the javascript function isn't picking up the new heights of the divs.
Any ideas?
You need to reset the height to auto before measuring it, or else it will always return the fixed value you set in $(document).ready:
function resizeTheDivs(tag){
// first get the tags to adjust
var $tags = $('.' + tag);
var $new_height = 0;
// find out which one is largest
$('.' + tag).each(function(){
$(this).removeAttr('style');
$(this).height() > $new_height ? $new_height = $(this).height() : null;
});
// make all others that height
$tags.height($new_height);
// I console.log($new_height) here sometimes
}
I have two divs "#sidebar-wrapper" and ".j1". I am finding the height of ".j1" on window load, j1 changes size according to its content, now I have to apply this height to "#sidebar-wrapper".
I have tried this
var currentHeight = 0;
$(window).load(function() {
//get the natural page height -set it in variable above.
currentHeight = $('.j1').outerHeight();
console.log("set current height on load = " + currentHeight);
$("#sidebar-wrapper").resize(currentHeight);
});
I don't know what to use to set height of "#sidebar-wrapper".
Try to use next code example in order to get and set attributes cause may be your $("#sidebar-wrapper") is not exists yet(length 0 in jquery object):
document.addEventListener('DOMContentLoaded', function() {
currentHeight = $('.j1').outerHeight();
console.log("set current height on load = " + currentHeight);
$("#sidebar-wrapper").css('height',currentHeight );
console.log($("#sidebar-wrapper").height());
}, false);
Have you tried to change the CSS attribute height of #sidebar-wrapper?
JsFiddle
$("#sidebar-wrapper").css("height", currentHeight);
.resize method seems to be an event triggered when changing the size of your window. You can find more information about the resize event here: Resize Event.
$( window ).resize(function() {
$( "#log" ).append( "<div>Handler for .resize() called.</div>" );
});
I have the following code below, it was modified from (CSS-Tricks Link). It works fine, however the magic line (floating element under navigation) in my site is 40 pixels wide.
I want to permanently center align the bar (whether it falls under hover state or not), at present it is aligned left of the element. As it is using the jQuery .position() to calculate from the left, all my efforts add the 'forceRight' but negate jQuery .position().
The variable 'forceRight', finds the difference either side of the 40px bar. However I need this side gap to be enforced as the menu items are different widths.
var forceRight,
off_hover_left,
$el,
$calcuateForceDistance,
$magicLine_width = 40,
$mainNav = $("#main-navigation"),
$currentPosition = $(".current-menu-item"),
$currentPosition_width = ($currentPosition.outerWidth() - $magicLine_width);
$mainNav.append("<span id='magic-line'></span>");
var $magicLine = $("#magic-line");
$magicLine
.css("left", $(".current-menu-item").position().left)
.data("origLeft", $magicLine.position().left);
$("#main-navigation a").hover(function(){
// current element
$el = $(this),
// Calcuate Distance
$calcuateForceDistance = Math.floor( ( $el.outerWidth() - $magicLine_width ) / 2 );
forceRight = ( $el.position().left + $calcuateForceDistance );
off_hover_left = Math.floor( $currentPosition.position().left + ($currentPosition_width / 2) );
$magicLine.stop().animate({
left: forceRight
});
}, function() {
// On Hover Out - Return to DOM LOAD (.current-menu-item)
$magicLine.stop().animate({
// not selected outerwidth !!! sort out variables above!
left: off_hover_left
});
});
Many thanks!
I have fixed the bug in my code, I also added a doc ready to get the code to run on browser rendering. When the code loads, I also created a delay then added a class to remove the glitch (the left animation between 0 -> needed axis value.
In this case I used opacity 0, as default. and 1, on .addClass('found').
var forceRight,
$el,
$calcuateForceDistance,
$magicLine_width = 40,
$mainNav = $("#main-navigation"),
$currentPosition = $(".current-menu-item"),
$currentPosition_width = ($currentPosition.outerWidth() - $magicLine_width),
$off_hover_left = Math.floor( $currentPosition.position().left + ($currentPosition_width / 2) );
// Create HTML ELEMENT
$mainNav.append("<span id='magic-line'></span>");
// Target -> Variable
var $magicLine = $("#magic-line");
// Apply attr's
$magicLine.css("left", $(".current-menu-item").position().left);
$(document).ready(function(){
// Enforce Code On Load
$magicLine.stop().animate({
// not selected outerwidth !!! sort out variables above!
left: $off_hover_left
}).promise().done(function(){
// Once Positioned - Then add class (changes opacity) !
$(this).addClass('found');
});
$("#main-navigation a").hover(function(){
// current element
$el = $(this),
// Calcuate Distance
$calcuateForceDistance = Math.floor( ( $el.outerWidth() - $magicLine_width ) / 2 );
forceRight = ( $el.position().left + $calcuateForceDistance );
$magicLine.stop().animate({
left: forceRight
});
}, function() {
// On Hover Out - Return to DOM LOAD (.current-menu-item)
$magicLine.stop().animate({
// not selected outerwidth !!! sort out variables above!
left: $off_hover_left
});
});
});
I hope this helps, someone not just me!
In your javascript you only set the left position of your #magic-line. You need to set the width of the line also. Example in the code underneath (Just the rows to modify):
// On the initialization
$magicLine
.css({
"left": $(".current-menu-item").position().left,
"width" : $(".current-menu-item").outerWidth()
});
// On modification
$magicLine.stop().animate({
left: leftPos,
width: $el.outerWidth()
});
This should solve the problem.
I would like to alter the hover direction based on the container size, if there's not enough space on the container to show the hover to the right, it should then show on the left.
See fiddle for details:
http://jsfiddle.net/jHgkp/3/
I use hoverIntent, but FULL details are on the Fiddle above:
$(document).ready(function(){
$(".discover").hoverIntent({
over: makeVisible,
out: makeInvisible,
timeout: 200
});
}); // close document.ready
function makeVisible() {
$(this).find('ul').fadeIn(100);}
function makeInvisible() {
$(this).find('ul').fadeOut(300);}
There are a few approches.
1) You can style the tooltip on the third element to show on the left side (not dynamic)
2) You can take the element offest().left + element.width + the tooltip width and compare it with the holder width. (dynamic)
3) Yo can the the tooltip offest + width and directly compare it to the holder width. (dynamic)
It depends what exactly you want...
This is the only JS added.
var holderWidth = $('.container').outerWidth();
and
//where 260 is left 150 + width 110
var pos = $(this).offset().left + 260
if(holderWidth < pos){
$(this).addClass('leftPos');
}else{
$(this).removeClass('leftPos');
}
and 1 line of css:
.leftPos ul { left: auto; right: 150px; }
Demo
I am trying to expand a div to a particular size on hover in and I want the div to go back to its original size on hover out, using the animate function.
Is there any way by which I could calculate the original size of the div to be used in animate?
You have to store the original state outside/before your eventhandler:
var origHeight = $("div").outerHeight(true);
$("div").hover(function(e){
$(this).stop().animate({
height: e.type === "mouseenter" ? $(window).height() : origHeight
});
});
http://jsfiddle.net/b5HUU/2/
By the way, it's not an good idea to do that on hover... Because there's no space for the mouse to leave (except the whole browser).
Update
So it's better to use a click-event:
var origHeight = $("div").outerHeight(true),
clickState = false;
$("div").click(function(e){
clickState = !clickState;
$(this).stop().animate({
height: clickState ? $(window).height() : origHeight
});
});
http://jsfiddle.net/b5HUU/4/
you need to stop animate on mouseenter and mouseleave
var w = $('#an').width(),
n = w + 100 ; // particular size
function widthAnimate( width ){
return function(){
$('#an').stop().animate({
width : width +'px',
});
}
};
$('#an').mouseenter( widthAnimate( n ) )
.mouseleave( widthAnimate(w ));
Added this in jsfiddle