Addclass when div width is greater than 80% - javascript

How to addclass when div width is greater than 80% ?
This is what I just tried
<div class="wrap_bar">
<div class="bar" style="width:50%;"></div>
</div>
<div class="box"></div>
<script>
var barTotal = $(".bar");
var box= $(".box");
var width = barTotal.width();
if (width > 80%)
box.addClass('type2')
</script>
This code is not working well. Please help

If you need this dimension detection only one time (when DOM loaded) then you can just following approach.
function addWhenResized(element){
var parentWidth = $(element).parent().width();
var elementWIdth = $(element).width();
if( (elementWIdth / parentWidth)*100 > 79){
$('.box').addClass('type2');
}
else {
$('.box').removeClass('type2');
}
}
$(document).ready(function(){
addWhenResized('.bar');
})
But main challenge will be there if you want detect the run time dimension change. Then need to take help from here: http://marcj.github.io/css-element-queries/
After added the plugins from above given link you should follow the following approach:
function addWhenResized(element){
var parentWidth = $(element).parent().width();
var elementWIdth = $(element).width();
if( (elementWIdth / parentWidth)*100 > 79){
$('.box').addClass('type2');
}
else {
$('.box').removeClass('type2');
}
}
new ResizeSensor(jQuery('.bar'), function(){
addWhenResized('.bar');
});

Try this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var barTotal = $(".bar");
var barTotalWidth = barTotal.width();
var box= $(".box");
var boxWidth = box.width();
var widthPercent = boxWidth / barTotalWidth;
console.log(widthPercent);
if (widthPercent > 0.8)
box.addClass('type2');
});
</script>
<div class="bar" style="width:200px;height:100px;background-color:red"> </div>
<div class="box" style="width:190px;height:80px;background-color:blue"> </div>

your codes don't work because you've just called javascript once when the page loaded , you have to wrap it into an event !
Take a look
that answer
or that answer

jQuery(document).ready(function($) {
if ($(this).width() > 768) {
$('#service-1').addClass('row text-center');
} else {
$('#service-1').removeClass('row text-center');
}
});
this will work fantastic when width is less than or more than will add or remove the class

Related

How do I add class to body when div height is smaller than window?

I'm trying to add a class to the body if a certain divs height is smaller than the users window size. Here is my current jQuery script. It doesn't work very well, and I don't get any errors. Not sure what I'm doing wrong.
Thanks
jQuery(document).ready(function($) {
var $window = $(window);
var $pageHeight = $('.wrap').height();
function checkWidth() {
var windowsize = $window.height();
if (windowsize < $pageHeight) {
$('body').addClass('need-padding');
}
}
checkWidth();
$(window).resize(checkWidth);
});
Try this... no need to create separate function :
$(window).resize(function(){
var $windowHeight = $(window).height();
var $blockHeight = $('.wrap').height();
if ($blockHeight < $windowHeight ) {
//console.log($windowHeight+" Window Height");
//console.log($blockHeight+" Block Height");
$('body').addClass('need-padding');
}
});
Generally, the code looks ok. But if your $('.wrap') has margins or borders, you might want to use use .outerHeight() instead of .height().
Here's a fiddle that shows what's going on:
http://jsfiddle.net/4fqb8t1q/
$(document).ready(function() {
checkWidth();
$(window).resize(checkWidth);
});
function checkWidth() {
var $pageHeight = $('.wrap').height();
alert($(window).height() + " < " + $pageHeight);
if ($(window).height() < $pageHeight) {
$('body').addClass('need-padding');
}
}

Moving a div right animation not working

I am trying implement a small animation on a div. Whenever we click on the div it has to move right. I wrote some code but it is not working. Could anyone please help me?
here is my code
<style type="text/css">
#animDiv
{
background-color:#6F0;
width:87px;
height:39px;
left:10px;
}
</style>
<script>
function $(id)
{
return document.getElementById(id);
}
function moveRight()
{
var elem = $("animDiv");
//var divPos = parseInt($("animDiv").style.left);
var divPos = $("animDiv").offsetLeft;
var divWid = $("animDiv").offsetWidth;
if(divPos+divWid < 700)
{
$("animDiv").style.left = $("animDiv").style.left+100+"px";
}
}
</script>
<body>
<div id="animDiv" onclick="moveLeft()">
</div>
</body>
try replacing this code
<div id="animDiv" onclick="moveLeft()">
with this code
<div id="animDiv" onclick="moveRight()">
and add style position:fixed; to your css.
There are several issues in your code:
You are calling the wrong function. It is declared moveRight()
You are attempting to change the left property which will have no affect on elements that are positioned statically.
The element will only nudge right one time. After that the value for your left property is something like 100px100px.
How is this:
function moveRight() {
var elem = $("animDiv");
//var divPos = parseInt($("animDiv").style.left);
var divPos = $("animDiv").offsetLeft;
var divWid = $("animDiv").offsetWidth;
if (divPos + divWid < 700) {
var curLeft = Number($("animDiv").style.left.replace("px", ""));
$("animDiv").style.left = (curLeft + 100) + "px";
}
}
JSFiddle

set height in relation to width

How do I set the height of an iframe by it's width?
<iframe width="100%" height="auto" id="youtube" ... >
window.onresize function() {
document.getElementById("youtube").style.height = this.style.width*0.63;
}
I'd like to use only javascript.
It looks like you aren't using window.onresize quite right by missing the equals sign to declare the function...
<iframe width="100%" height="auto" id="youtube" ... >
window.onresize = function(event) {
document.getElementById("youtube").style.height = document.getElementById("youtube").style.width*0.63;
}
You can create an interval that run in the background and updates the frame to match.
function autoAdjustWidth(){
var frm=document.getElementById('myFrame');
console.log(frm.offsetWidth);
frm.height=frm.offsetWidth;
}
autoAdjustWidth();
window.setInterval(autoAdjustWidth,300);
See jsfiddle.
Your example looks almost correct with a few changes:
// using =
window.onresize = function() {
var iFrame = document.getElementById("youtube");
// use iFrame width instead of "this" which is the windows width
iFrame.style.height = iFrame.style.width;
}
var player = null;
$( document ).ready(function() {
resizeHeroVideo();
} );
$(window).resize(function() {
resizeHeroVideo();
});
function resizeHeroVideo() {
var content = $('#hero');
var contentH = viewportSize.getHeight();
contentH -= 158;
content.css('height',contentH);
if(player != null) {
var iframe = $('.videoWrapper iframe');
var iframeH = contentH - 150;
if (isMobile) {
iframeH = 163;
}
iframe.css('height',iframeH);
var iframeW = iframeH/9 * 16;
iframe.css('width',iframeW);
}
}
Complete gist here. Live example here.

Find element that's on the middle of the visible screen (viewport), on scroll

I need to know if there is a way I can determine if a div is in the center of the screen.
HTML:
<div id="container">
<div class="box" id="box0">
text
</div>
<div class="box" id="box1">
text
</div>
.....
<div class="box" id="box100">
text
</div>
</div>
Is there a way to determine when a div will be in the center of the visible screen, considering that the page is scrollable? So basically, when the user is scrolling down the page, the div that's in the middle of the visible screen should be selected.
Thanks
DEMO PAGE
var findMiddleElement = (function(docElm){
var viewportHeight = docElm.clientHeight,
// here i'm using pre-cached DIV elements, but you can use anything you want.
// Cases where elements are generated dynamically are more CPU intense ofc.
elements = $('div');
return function(e){
var middleElement;
if( e && e.type == 'resize' )
viewportHeight = docElm.clientHeight;
elements.each(function(){
var pos = this.getBoundingClientRect().top;
// if an element is more or less in the middle of the viewport
if( pos > viewportHeight/2.5 && pos < viewportHeight/1.5 ){
middleElement = this;
return false; // stop iteration
}
});
console.log(middleElement);
}
})(document.documentElement);
$(window).on('scroll resize', findMiddleElement);
Another way (for modern browsers only) is to use the intersection API
This is nice method: elementFromPoint()
You can get the element in the center as so:
var elem = document.elementFromPoint($(window).width()/2, $(window).height()/2);
//if you want jquery element you can get it.
var jqueryElem = $(elem);
The height of the window and the scrollTop() of the window will give you the range of offsets that exist in the users view:
var minHeight = $(window).scrollTop()
var maxHeight = $(window).height()
var middleHeight = (maxHeight + minHeight) / 2;
You could try using a viewport selector such as:
http://www.appelsiini.net/projects/viewport
This will give you all visible elements. A plugin isn't needed but will ease the selection
var visibleElements = $("div.box").filter(":in-viewport")
From this selection you can then look for the element closest to the middleHeight:
var $midElement;
var distance = null;
var currDistance = 0;
visibleElements.each(function(index, element) {
currDistance = Math.abs(middleHeight - $midElement.offset().top);
if ( distance == null || currDistance < distance ) {
$midElement = $(element);
distance = currDistance;
}
});
Haven't tested this but it should be along the right track.

javascript check document for element to apply a value

i'm pretty new to javascript and have been stuck on this all day. I have a script which resize element according to screen res it all works except I need to have "if element DOES NOT exist on document then add an addittional value "242px" into contentContainer.css method" this is what I have so far so that this eleemnt takes up the space of the asideContent element when its not on the page...
<script>
// DOM Container Resize Handler
var extra = ($("body.asideContent").length == 0) ? 242 : 0;
var adjustStyle = function() {
var winWidth = $(window).width(),
width = parseInt(winWidth),
container = $('body .fixed');
contentContainer = $('body .content');
if (width >= 1454) {
container.css('width','1454px');
contentContainer.css('width',extra + 1210 + "px");
} else if ((width < 1454) & (width >= 1212)) {
container.css('width','1212px');
contentContainer.css('width',extra + 968 + "px");
} else {
container.css('width','970px');
contentContainer.css('width',extra + 726 + "px");
}
};
$(function() {
var filterWrap = $("#filterWrap"),
offset = filterWrap.offset(),
topPadding = 15;
$(window).scroll(function() {
if ($(window).scrollTop() > offset.top) {
filterWrap.stop().animate({
marginTop: $(window).scrollTop() - offset.top + topPadding
});
} else {
filterWrap.stop().animate({
marginTop: 0
});
};
});
// DOM Container Resize Handler - Initialization
$(window).resize(function() {
adjustStyle();
});
adjustStyle();
});
</script>
Its applying the extra all the time, add I only want to apply this when ("body.asideContent") is not in the document
test html
<html>
<head>
</head>
<body>
<div class="fixed">
<div id="container">
<div class="asideContent">&nbsp</div>
<div class="content">&nbsp</div>
</div>
</div>
</body>
</html>
Just want to say thank you in advance for any help you can give me... its been driving me crazy all day...
body.asideContent means a body with a class of asideContent. Try
$("body .asideContent")
(aka, with a space between body and .asideContent)

Categories

Resources