I am trying to have a div change its properties on a click function. Some of the properties I am changing with a call to toggleClass() which is fine and works great. However I also want to resize the div based on the size of the viewport. In order to have access to those numbers I am changing the width and height with jQuery. This command looks like this:
$('.box').click( function() {
$(this).toggleClass('box--grow', 0);
$(this).css('width', w * .9);
$(this).css('height', h * .9);
});
EDIT I want the height and width to go back to 100%.
I tried using the toggle class but that caused the entire div to disappear, and this solution doesn't work because when I click the div again the class is removed but the height is the same.
I am looking for a way to toggle this or to get the viewport width within the css. I tried both approaches but couldn't get anything to what I am looking for.
why not using CSS VH and VW values?
CSS:
.my90Class{
width: 90vw;
height: 90vh;
}
JS:
$('.box').click( function() {
$(this).toggleClass("my90Class");
});
You need to get the window size first, and then put everything into combined .ready() and .resize() functions, to make it responsive.
function myfunction() {
var w = $(window).width();
var h = $(window).height();
$('.box').click(function () {
if ($(this).hasClass('box--grow')) {
$(this).removeClass('box--grow');
$(this).css({
'width': '',
'height': ''
});
} else {
$(this).addClass('box--grow');
$(this).css({
'width': w * .9,
'height': h * .9
});
}
});
}
$(document).ready(myfunction);
$(window).on('resize', myfunction);
jsfiddle
You can check for the class with:
$(this).hasClass('box--grow')
Then to remove the class:
$(this).removeClass('box--grow');
And to add it back again:
$(this).addClass('box--grow');
The end would look like this save the original width and height before the event so you can add it back again:
var oldwidth = $('.box').css('width');
var oldheight = $('.box').css('height');
$('.box').click( function() {
if($(this).hasClass('box--grow')) {
$(this).removeClass('box--grow');
$('.box').css('width', oldwidth);
$('.box').css('height', oldheight);
} else {
$(this).addClass('box--grow');
}
});
untested but it would probably work
Related
I have a banner image that is only visible when i set a fixed height, i want to make it responsive so the only way i thought of doing that is calculating the height of the image with the width of the window.
the function to calculate the height is: windowWidth/1.845
how do i apply that function to a div css with jquery/javascript?
i tried this function but it didn't work
$(document).ready(function(){
var originalWidth = $( window ).width();
var newHeight = originalWidth/+(1.845)
;
function resize() {
$("#ei-slider").css("height", newHeight);
}
$(".target").each(resize);
$(document).resize(function(){
$("ei-slider").each(resize);
});
});
Try adding () when you call your function resize
$(".target").each(resize());
$(document).resize(function(){
$(".ei-slider").each(resize());
});
Also, you miss the point before ei-slider
And I highly recommend to you to use backstretch jquery plugin.
http://srobbin.com/jquery-plugins/backstretch/
Why is the image only visible when you set a fixed height? An image would be "responsive" automatically if you were to do this in your CSS.
img {
max-width: 100%;
width: 100%;
}
However if you need to do other things in the resize you probably want to listen for resizes on window and not document.
$(document).ready(function () {
var $window = $(window);
var originalWidth = $window.width();
var newHeight = originalWidth / 1.845;
function resize() {
// This will be .target or .ei-slider based on where it's called.
$(this).css("height", newHeight);
};
$(".target").each(resize);
$window.on('resize', function(){
$(".ei-slider").each(resize);
});
});
Situation:
I'm working on a responsive design that involves the typical HTML/CSS combo. Everything is working nicely except in one case where there is an iframe inside of a div. The iframe should adjust automatically to the size of the parent div. A purely css solution has not presented itself so I'm going with a JQuery approach. It works nicely except in one scenario, when resizing from a smaller width to a larger width screen.
HTML:
<div class="container">
<iframe class="iframe-class" src="http://www.cnn.com/"></iframe>
</div>
CSS:
.container {
width: 100%;
height: 250px;
}
.iframe-class {
width: 100%;
height: 100%;
border: 1px solid red;
overflow: auto;
}
Javascript:
$(function () {
setIFrameSize();
$(window).resize(function () {
setIFrameSize();
});
});
function setIFrameSize() {
var ogWidth = 700;
var ogHeight = 600;
var ogRatio = ogWidth / ogHeight;
var windowWidth = $(window).width();
if (windowWidth < 480) {
var parentDivWidth = $(".iframe-class").parent().width();
var newHeight = (parentDivWidth / ogRatio);
$(".iframe-class").addClass("iframe-class-resize");
$(".iframe-class-resize").css("width", parentDivWidth);
$(".iframe-class-resize").css("height", newHeight);
} else {
// $(".iframe-class-resize").removeAttr("width");
// $(".iframe-class-resize").removeAttr("height");
$(".iframe-class").removeClass("iframe-class-resize");
}
}
http://jsfiddle.net/TBJ83/
Problem:
As the window is resized smaller, it continually checks the window width and once it hits < 480 px, the code adds a class called iframe-class-resize and sets the width and height to that class. As the window is resized larger, it removes the class once the size hits 480 px. The problem is that setting the width and height attributes adds them directly to the element and not the class itself. Therefore, removing the class does not remove the new width and heights. I tried to force removing the attributes using removeAttr() (commented out above) but that didn't work.
Anyone see where the code above went wrong? Or any suggestions on how to accomplish having a responsive iframe more effectively? The main things that are required are that the iframe has to be inside the <div></div> and the div may not necessarily have a width or height defined. Ideally, the parent div should have the width and height explicitly defined but the way this site is currently setup, that won't always be possible.
Additional:
In case the above wasn't clear enough, try the following to reproduce the issue:
Open up a browser on a desktop machine. I'm using Chrome on a Windows machine. Don't maximize the browser.
Open up the jsfiddle above (http://jsfiddle.net/TBJ83/). You'll notice that the iframe content spans the entire width of the Preview panel.
Manually resize the width down until the entire window is < 480px. At this point, the iframe content will be pretty tiny.
Manually resize the width back up until the entire window is >> 480px. The goal is to have that iframe content to regain the entire width of the Preview panel. Instead, the content is retaining the resized width and height since the .css() function applies css changes directly to elements rather than to the classes.
Thanks in advance!
You can do this in about 30 characters. Change:
$(".iframe-class").removeClass("iframe-class-resize")
to:
$(".iframe-class").removeClass("iframe-class-resize").css({ width : '', height : '' })
This will reset the width/height you applied to the element. When you use .css() you add whatever you pass-in to the style attribute of the element. When you pass a blank value, jQuery removes that property from the style attribute of the element.
Here is an updated fiddle: http://jsfiddle.net/TBJ83/3/
EDIT
OK, here's something tweaked for performance (and just some other ways to do things):
$(function () {
//setup these vars only once since they are static
var $myIFRAME = $(".iframe-class"),//unless this collection of elements changes over time, you only need to select them once
ogWidth = 700,
ogHeight = 600,
ogRatio = ogWidth / ogHeight,
windowWidth = 0,//store windowWidth here, this is just a different way to store this data
resizeTimer = null;
function setIFrameSize() {
if (windowWidth < 480) {
var parentDivWidth = $myIFRAME.parent().width(),//be aware this will still only get the height of the first element in this set of elements, you'll have to loop over them if you want to support more than one iframe on a page
newHeight = (parentDivWidth / ogRatio);
$myIFRAME.addClass("iframe-class-resize").css({ height : newHeight, width : parentDivWidth });
} else {
$myIFRAME.removeClass("iframe-class-resize").css({ width : '', height : '' });
}
}
$(window).resize(function () {
//only run this once per resize event, if a user drags the window to a different size, this will wait until they finish, then run the resize function
//this way you don't blow up someone's browser with your resize function running hundreds of times a second
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function () {
//make sure to update windowWidth before calling resize function
windowWidth = $(window).width();
setIFrameSize();
}, 75);
}).trigger("click");//run this once initially, just a different way to initialize
});
This can be done using pure CSS as below:
iframe {
height: 300px;
width: 300px;
resize: both;
overflow: auto;
}
Set the height and width to the minimum size you want, it only seems to grow, not shrink.
This is how I would do it, code is much shorter: http://jsfiddle.net/TBJ83/2/
<div class="container">
<iframe id="myframe" src="http://www.cnn.com/"></iframe>
</div>
<script>
$(function () {
setIFrameSize();
$(window).resize(function () {
setIFrameSize();
});
});
function setIFrameSize() {
var parentDivWidth = $("#myframe").parent().width();
var parentDivHeight = $("#myframe").parent().height();
$("#myframe")[0].setAttribute("width", parentDivWidth);
$("#myframe")[0].setAttribute("height", parentDivHeight);
}
</script>
I did it that way for read-ability, but you could make it even shorter and faster...
function setIFrameSize() {
f = $("#myframe");
f[0].setAttribute("width", f.parent().width());
f[0].setAttribute("height", f.parent().height());
}
One selector, so you only look through the DOM once instead of multiple times.
For those using Prestashop, this is how I used the code.
In the cms.tpl file I added the below code:
{if $cms->id==2}
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
<script type="text/javascript" src='../themes/myheme/js/formj.js'></script>
<div style="width: 100%; height: 800px;">
<iframe style=" width: 100%; height: 100%; border: overflow: auto;" src="https://cnn.com"></iframe>
</div>
{/if}
Then created a new js file: formj.js and added the below code:
$(function () {
//setup these vars only once since they are static
var $myIFRAME = $(".iframe-class"),//unless this collection of elements changes over time, you only need to select them once
ogWidth = 970,
ogHeight = 800,
ogRatio = ogWidth / ogHeight,
windowWidth = 0,//store windowWidth here, this is just a different way to store this data
resizeTimer = null;
function setIFrameSize() {
if (windowWidth < 480) {
var parentDivWidth = $myIFRAME.parent().width(),//be aware this will still only get the height of the first element in this set of elements, you'll have to loop over them if you want to support more than one iframe on a page
newHeight = (parentDivWidth / ogRatio);
$myIFRAME.addClass("iframe-class-resize").css({ height : newHeight, width : parentDivWidth });
} else {
$myIFRAME.removeClass("iframe-class-resize").css({ width : '', height : '' });
}
}
$(window).resize(function () {
//only run this once per resize event, if a user drags the window to a different size, this will wait until they finish, then run the resize function
//this way you don't blow up someone's browser with your resize function running hundreds of times a second
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function () {
//make sure to update windowWidth before calling resize function
windowWidth = $(window).width();
setIFrameSize();
}, 75);
}).trigger("click");//run this once initially, just a different way to initialize
});
Let's say I have an image, cat.jpg, and when clicked I want to clone it.
$('img.cat').on("click", function() {
$(this).clone().appendTo('#container');
});
Upon duplication, however, I want the new cat.jpg to appear as half the size of the original. And I want this to continue happening each time a new cat.jpg is clicked.
Any ideas on how to go about accomplishing this? Is it even possible to inject new styling/classes/parameters via .clone()?
It sounds like the following is what you're after:
// If all images are within #container, use $("#container") instead:
$(document).on("click", "img.cat", function () {
var original = $(this);
original.clone().css({
width: original.width() / 2,
height: original.height() / 2
}).appendTo("#container");
});
Fiddle: http://jsfiddle.net/G6XTz/
Of course, you may have wanted the newly added image to be half the size of the last cat image, rather than the cat image clicked:
Fiddle2: http://jsfiddle.net/G6XTz/1/
Caveat:
The width and height can only divide so far; eventually you'll run into some problems. Better check the result of division first, and make a decision to do something else when it makes sense.
Just setting the width to half seems to be enough with an img element, the height gets set automatically in proportion to the width:
$('#container').on('click','img.cat', function() {
$(this).clone()
.appendTo('#container')
.width(function(i,v) { return v/2;});
});
Demo: http://jsfiddle.net/Mr2x8/
But if you find you need to set the width and the height here's one way to do it:
$('#container').on('click','img.cat', function() {
var $this = $(this);
$this.clone()
.appendTo('#container')
.width($this.width()/2)
.height($this.height()/2);
});
Demo: http://jsfiddle.net/Mr2x8/1/
id do this:
$(this).clone().addClass('small').appendTo('#container');
this adds the css class small to the clone of this.
Create a new class with the specific new styling you want to get changed dynamicaly in your CSS file.
.newClass {
//example green outline
outline: solid thin green;
}
And then modify your script:
$('img.cat').on("click", function() {
$(this).clone().addClass('newClass').appendTo('#container');
});
EDIT :
If the only thing you want to change is the size of the img for lets say 10% each click then:
$('img.cat').on("click", function() {
var width = $(this).width() * 0.9;
var height = $(this).height() * 0.9;
$(this).clone().css({"width":width+"px", "height":height+"px"}).appendTo('#container');
});
The above code will produce the same image but 10% smaller than the image clicked .
If you want to click only the initial image then simply put the width and height variable outside the click function and update them inside for each click.
NOTE :
In the css() you add +"px" if initial width is in px else you add +"%" if it is in percentage.
I have a container within my body and I need to set this element to centered vertical alignment. I need to do this also dependent on body height, and change it dynamically.
I tried with something like the below code, but it doesn't work perfectly and most importantly not dynamic. Note: I can't do this with css.
var ah = $('body').height();
var ph = $('#main_container').parent().height();
var mh = Math.ceil((ph-ah) / 2);
$('#main_container').css('margin-top', mh);
Bind it to the resize event:
$(window).on('resize', function() {
var $container = $('#main_container');
var height = Math.ceil(($container.parent().height() - $('body').height()) / 2);
$container.css({marginTop: height});
}).trigger('resize');
It won't be as smooth as CSS, but it will work. Why can't you do it with CSS?
You can inject CSS using JQuery:
$('#main_container').css("position", "absolute");
$('#main_container').css("margin-top", "auto");
$('#main_container').css("margin-bottom", "auto");
$('#main_container').css("top", 0);
$('#main_container').css("bottom", 0);
If you also want to horizontally center it, you can delete the margin-top and margin-bottom lines, and add:
$('#main_container').css("margin", "auto");
$('#main_container').css("left", 0);
$('#main_container').css("right", 0);
I am using zepto library for my mobile web site. I have recently learnt that zepto does not have slideDown() plugin like jquery. I would like to implement the same for zepto.
I have tried one on jsfiddle (http://jsfiddle.net/goje87/keHMp/1/). Here it does not animate while showing the element. It just flashes down. How do I bring in the animation?
PS: I cannot provide a fixed height because I would be applying this plugin to the elements whose height property would not be known.
Thanks in advace!!
Demo: http://jsfiddle.net/6zkSX/5
JavaScript:
(function ($) {
$.fn.slideDown = function (duration) {
// get old position to restore it then
var position = this.css('position');
// show element if it is hidden (it is needed if display is none)
this.show();
// place it so it displays as usually but hidden
this.css({
position: 'absolute',
visibility: 'hidden'
});
// get naturally height
var height = this.height();
// set initial css for animation
this.css({
position: position,
visibility: 'visible',
overflow: 'hidden',
height: 0
});
// animate to gotten height
this.animate({
height: height
}, duration);
};
})(Zepto);
$(function () {
$('.slide-trigger').on('click', function () {
$('.slide').slideDown(2000);
});
});
This worked for me:
https://github.com/Ilycite/zepto-slide-transition
The Zepto Slide Transition plugin add to Zepto.js the functions bellow :
slideDown();
slideUp();
slideToggle();
Speransky's answer was helpful, and I'm offering a simplified alternative for a common drop-down navigation list, and separated into slideUp and slideDown on jsfiddle: http://jsfiddle.net/kUG3U/1/
$.fn.slideDown = function (duration) {
// show element if it is hidden (it is needed if display is none)
this.show();
// get naturally height
var height = this.height();
// set initial css for animation
this.css({
height: 0
});
// animate to gotten height
this.animate({
height: height
}, duration);
};
This would work for what you need:
https://github.com/NinjaBCN/zepto-slide-transition