Color will not change when scrolling - javascript

i am trying to implement a feature on a menu that i am working on.When i scroll more than 50 pixels, let's say, i want to make the background color black, for example. Here is my code:
function myFunction() {
var x = document.getElementById("test");
if ( document.body.scrollTop > 50 || document.documentElement.scrollTop > 50 ) {
x.classList.toggle("change");
}
}
#test {
background-color: #d2d2d2;
height: 90px;
position: fixed;
top: 0px;
left: 0px;
}
.change {
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onscroll="myFunction()">
<div id="test">
<p>
Wow, this is some really nice text, now isn't it?
</p>
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div id="demo">
Kachow, another text.
</div>
</body>
As you can see, the background colour won't change. If you look at the CSS rules, you can see that the extra colour is added, but crossed off (in FireFox). Would you know why?
JSFiddle Demo: https://jsfiddle.net/TakeDown/7djmqkzL/12/.
Thank you for your time!

The id selector has a higher specificity than a plain class selector. Meaning your class css won't override the id one. So you need to create a selector that has a higher specificity, and in your case just tag on the id selector:
#test.change {
background-color:black;
}
If you don't want to tie it to a particular id, you can tag on the element name instead to make the specificity higher
div.change {
background-color:black
}
Can read more about css selector specificity on MDN or in the spec at here
Demo
function myFunction() {
var x = document.getElementById("test");
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
x.classList.add("change");
} else {
x.classList.remove("change");
}
}
#test {
background-color: #d2d2d2;
height: 90px;
position: fixed;
top: 0px;
left: 0px;
}
#test.change {
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onscroll="myFunction()">
<div id="test">
<p>
Wow, this is some really nice text, now isn't it?
</p>
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div id="demo">
Kachow, another text.
</div>
</body>

If you want to get rid of graphical glitches don't use toggle
x.classList.toggle("change");
Instead, just set it to black when the scroll is 50
x.style.background = "black";

Related

Javascript & CSS/HTML - Background Change on Mouse Over of DIV

I have the following code in my HTML.
<div class="bg"></div>
<div class="content" id="hover">
<div class="one" id="hover-over">1</div> <!--Trigger!-->
<div class="two">2</div>
<div class="three">3</div>
<div class="four">4</div>
<div class="five">5</div>
</div>
The CSS..
.bg {
background: yellow;
position: fixed;
top: 0;
left: 0;
z-index: 1;
}
.content {
background: red;
}
The Javascript..
var box = document.getElementById("bg");
var bgChanger = document.getElementById("hover-over");
//var body = document.getElementsByTagName("body");
function changeBackgroundUp() {
box.style.backgroundColor = "blue";
//body.style.backgroundColor = "#6fcc6f";
}
function changeBackgroundDown() {
box.style.backgroundColor = "green";
//body.style.backgroundColor = "red";
}
bgChanger.onmouseover = changeBackgroundUp; //
bgChanger.onmouseleave = changeBackgroundDown; //
A Fiddle: https://jsfiddle.net/bqnw4qyb/56/
The Problem
I wish to have the background of the project CHANGED to, for example, green - when the user hovers over one of the DIV elements inside "content". So, when the user hovers over "1", the background of the whole page will change to green. My DIV elements have the background of RED, I don't want this colour to change, only the background color, ideally I would want to change the background to an image using a
background: url('someImage');
type of system..
I have tried many existing solutions, such as using CSS hover:
.one:hover ~ .bg {
background: url('someImage')
}
At this stage I am stumped, so any help is very much appreciated.
function green() {
document.getElementsByClassName("content")[0].style.backgroundColor = "green";
}
function red() {
document.getElementsByClassName("content")[0].style.backgroundColor = "red";
}
.bg {
background-color: yellow;
position: fixed;
top: 0;
left: 0;
z-index: 1;
}
.content {
background: red;
}
<div class="bg"></div>
<div class="content" id="hover">
<div class="one" onmouseover="green()" onmouseout="red()" id="hover-over">1</div> <!--Trigger!-->
<div class="two">2</div>
<div class="three">3</div>
<div class="four">4</div>
<div class="five">5</div>
</div>
Please see how I implemented this, is this what you would like?
My program is using the onmouseover and the onmouseout event.
Please leave any concerns in the comments, hope it helped ;)
Check the error console!
You have no box object as you have no element with id bg only class.
Add add the id to the div with class bg as well.
<div class="bg" id="bg"></div>
Also with your current positioning, the bg div is not actually visible.
https://jsfiddle.net/bqnw4qyb/67/

Get height of element then add class/change css

I'm trying to get the height of every h2 in a div, then if that height is higher than 21px, apply a class to that h2 or change his css.
The reason for that is that I have my project titles overlapping the tags when they're longer than a single line :
http://www.elisagilis.be
so far I've tried this :
$('.post-details h2').each(function(){
if($(this).height() > 21)
{
$(this).css({"margin-top": "315px", "line-height": "28px"});
}
});
AND this :
$('.post-details h2').each(function(){
if($(this).height() > 21)
{
$(this).addClass('margintop');
}
});
None of them work.
I've tried without using each as well, didn't work because it would select all of my h2 and apply the css/class to all of them.
- if you have a better solution than the ones I'm considering they're welcome as well.
Many thanks for your help!
I think this is what you are looking for
<h2>some text</h2>
<h2>some text<br>some more</h2>
.border {border:1px solid blue;}
$('h2').each(function(){
alert($(this).height());
if($(this).height() > 30)
{
$(this).addClass('border');
}
});
Just change it to your preferences.
https://jsfiddle.net/370mg7ak/1/
maybe this is what you want: FIDDLE
HTML
<div class="cta">
<span class="cta-title">one line</span>
</div>
<div class="cta">
<span class="cta-title">one line</span>
</div>
<div class="cta">
<span class="cta-title">this will take up two lines</span>
</div>
CSS
.cta { width: 100px; float: left; height: 100px; border: 1px solid black; }
.cta-title { width: 100%; color: white; background: black; display: inline-block; }
.two-line { background-color: red; }
jQuery
$(document).ready(function() {
$(function(){
var $tArray = $('div.cta').children('span');
$tArray.each(function(){
if ($(this).height() > 18) {
$(this).addClass('two-line');
}
});
});
});
In order to make the values change dynamically as the window is resizing, try this:
$(window).on("resize", ".post-details h2", function(){
if($(this).height() > 21)
{
$(this).addClass('margintop');
}
});
This attaches to the window's onresize event and filters the events based on the ".post-details h2" selector. However, in this case you may also have to account for if the page size is made larger again, then you also need the initialize case.
//Initial setup
$(".post-details h2").each(function(){
if($(this).height() > 21)
$(this).addClass('margintop');
});
//On window resize
$(window).on("resize", ".post-details h2", function(){
if($(this).height() > 21)
$(this).addClass('margintop');
else
$(this).removeClass('margintop');
});
I would probably remove the position:absolute; from the <p> tag and let the elements flow naturally. This way you won't have to worry about maintaining any extra javascript.
To get the 20px padding you have at the bottom you could add this style:
.post-details > a, .post-details p { transform: translateY(-20px); }
Replace the following code
$('.post-details h2').each(function(){
if($(this).height() > 21)
{
$(this).css({"margin-top": "315px", "line-height": "28px"});
}
});
with
$(function(){
$('.post-details h2').each(function(){
if($(this).height() > 21)
{
$(this).css({"margin-top": "315px", "line-height": "28px"});
}
});
});
I ended up grouping my elements in a single div that I positioned with css only.

Toggle display:none with div in front of another div?

I'm trying to make a div that I have on top of another div show up when you click on something.
This is the code for the two divs, without all the stuff that's within each:
<div id="randomarticle_enlarge">
<h1></h1>
<h4></h4>
<p></p>
<p></p>
</div>
<div class="bodybag">
<h1></h1>
<h4></h4>
<p></p>
<p></p>
</div>
Then I have css for each, of course:
.bodybag {
width:960px;
}
#randomarticle_englarge {
height:750px;
width:960px;
position:absolute;
z-index:2;
margin-top:1px;
padding-left:20px;
padding-right:20px;
display: none;
}
Am I supposed to have the bodybag class have a z-index and a position:relative? Because even though I don't it's working (at this point).
Anyway, I have this script written that's doing exactly what I want it to do:
$(document).ready(function() {
$('.popular').click(function() {
$('#textmask').fadeTo( 'fast', 0.1);
$('#backgroundmask').css('background-color', 'white');
});
});
And all I want to happen next is that as the textmask and the backgroundmask fade in/change as they should and do, is for the randomarticle_enlarge div to show up.
I've tried using .toggle and .toggleClass and .slideToggle and .show but nothing is working.
Absolute positioning must be relative to a container. In order to absolutely position something you need to indicate what it's absolutely positioned to. Something along these lines.
<div id="randomarticle_englargeContainer">
<div id="randomarticle_englarge">
</div>
<div class="bodybag">
</div>
</div>
#randomarticle_englargeContainer {
position: relative;
}
.bodybag {
position: absolute;
left: 0;
top: 0;
}
When copying everything from above I have no issues using $('#randomarticle_englarge').toggle();. Check your browser's console for errors; you might find the answers there.
I'm not exactly sure about what would you like to do with the divs, but I created an example for you, maybe this is what you want:
LIVE DEMO
So there is two divs. The 2nd div covers the 1st one. Clicking on a 'button' hides the 2nd div, so the 1st one reveals. Clicking again the 'button', the 2nd div appears and covers the 1st one again.
HTML:
<div class="popular">Click me!</div>
<div class="container">
<div id="randomarticle_enlarge">
<h1>A</h1>
<h4>B</h4>
<p>C</p>
<p>D</p>
</div>
<div class="bodybag">
<h1>E</h1>
<h4>F</h4>
<p>G</p>
<p>H</p>
</div>
</div>
CSS:
.container {
position: relative;
}
.bodybag {
width: 100px;
height: 200px;
background-color: red;
}
#randomarticle_enlarge {
width: 100px;
height: 200px;
background-color: green;
position: absolute;
top: 0;
left: 0;
}
.hide {
display: none;
}
jQuery:
$(document).ready(function() {
$('.popular').click(function() {
$('#randomarticle_enlarge').toggleClass('hide');
});
});

Display value in jQueryUI ProgressBar

I've set up a simple jQuery UI ProgressBar:
<script type="text/javascript">
$(function() {
$("#progressbar").progressbar({
value: 35
});
});
</script>
<div id="progressbar"> </div>
Among other things, I'd like to display some text in the progress-bar (for starters, I'd just use the "value").
I can't seem to get this to work.
Bonus Question: How do I format the displayed text (e.g. color, alignment)?
Instead of introducing another element (span) and a new style, leverage what is already there like this:
var myPer = 35;
$("#progressbar")
.progressbar({ value: myPer })
.children('.ui-progressbar-value')
.html(myPer.toPrecision(3) + '%')
.css("display", "block");
The css("display", "block") is to handle the case where the value is 0 (jQuery UI sets a display: none on the element when the value is 0).
If you look at the source of The demo, you'll notice that a <div class="ui-progressbar-value"> is added. You can simply override this class in your own CSS, like:
.ui-progressbar-value {
font-size: 13px;
font-weight: normal;
line-height: 18px;
padding-left: 10px;
}
The way I did it was:
<div class="progressbar"><span style="position:absolute; margin-left:10px; margin-top:2px>45% or whatever text you want to put in here</span></div>
You can adjust the margin-top and margin-left so that the text is in the center of the progress bar.
Then you apply the progressbar plugin for the elements which have class progressbar in the javascript section of the page
Hope this help
After fiddling around with some solutions, based on the answers here, I've ended up with this one:
Html:
<div id="progress"><span class="caption">Loading...please wait</span></div>
JS:
$("#progress").children('span.caption').html(percentage + '%');
(To be called inside the function that updates the progressbar value)
CSS:
#progress {
height: 18px;
}
#progress .ui-progressbar {
position: relative;
}
#progress .ui-progressbar-value {
margin-top: -20px;
}
#progress span.caption {
display: block;
position: static;
text-align: center;
}
Advantages:
Caption is centered with no harcoded positioning (necessary if caption width changes dinamically)
No JS strange manipulation
Simple and minimal CSS
This solution allows for a flexible width based on the text as well as centering the text, styling the text, etc. Works in Chrome, FF, IE8, and IE8 in compatibility mode. Didn't test IE6.
Html:
<div class="progress"><span>70%</span></div>
Script:
$(".progress").each(function() {
$(this).progressbar({
value: 70
}).children("span").appendTo(this);
});
CSS:
.progress.ui-progressbar {position:relative;height:2em;}
.progress span {position:static;margin-top:-2em;text-align:center;display:block;line-height:2em;padding-left:10px;padding-right:10px;}
.progress[aria-valuenow="0"] span {margin-top:0px;}​
Working sample: http://jsfiddle.net/hasYK/
I used this:
<div id="progressbar" style="margin: 0px 0px 16px 0px; "><span style="position: absolute;text-align: center;width: 269px;margin: 7px 0 0 0; ">My %</span></div>
<style>
#progress {
height: 18px;
}
#progress .ui-progressbar {
position: relative;
}
#progress .ui-progressbar-value {
margin-top: -20px;
}
#progress span.caption {
display: block;
position: static;
text-align: center;
}
</style>
</head>
<body>
test
<div id="progressbar"></div>
<br>
test2
<div id="progressbar2"></div>
<script>
$("#progressbar").progressbar({
max : 1024,
value : 10
});
$("#progressbar2").progressbar({
value : 50
});
$(document).ready(function() {
$("#progressbar ").children('div.ui-progressbar-value').html('10');
$("#progressbar2 ").children('div.ui-progressbar-value').html('50%');
});
</script>
</body>

How do I achieve equal height divs (positioned side by side) with HTML / CSS ?

I have two divs inside of a container. One on the left, one on the right, side by side. How am I able to make each one be of equal height, even though they have different content.
For example, the right div has a lot of content, and is double the height of the left div, how do I make the left div stretch to the same height of the right div?
Is there some JavaScript (jQuery) code to accomplish this?
You could use jQuery, but there are better ways to do this.
This sort of question comes up a lot and there are generally 3 answers...
1. Use CSS
This is the 'best' way to do it, as it is the most semantically pure approach (without resorting to JS, which has its own problems). The best way is to use the display: table-cell and related values. You could also try using the faux background technique (which you can do with CSS3 gradients).
2. Use Tables
This seems to work great, but at the expense of having an unsemantic layout. You'll also cause a stir with purists. I have all but avoided using tables, and you should too.
3. Use jQuery / JavaScript
This benefits in having the most semantic markup, except with JS disabled, you will not get the effect you desire.
Here's a way to do it with pure CSS, however, as you'll notice in the example (which works in IE 7 and Firefox), borders can be difficult - but they aren't impossible, so it all depends what you want to do. This example assumes a rather common CSS structure of body > wrapper > content container > column 1 and column 2.
The key is the bottom margin and its canceling padding.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Equal Height Columns</title>
<style type="text/css">
<!--
* { padding: 0; margin: 0; }
#wrapper { margin: 10px auto; width: 600px; }
#wrapper #main_container { width: 590px; padding: 10px 0px 10px 10px; background: #CCC; overflow: hidden; border-bottom: 10px solid #CCC; }
#wrapper #main_container div { float: left; width: 263px; background: #999; padding: 10px; margin-right: 10px; border: 1px solid #000; margin-bottom: -1000px; padding-bottom: 1000px; }
#wrapper #main_container #right_column { background: #FFF; }
-->
</style>
</head>
<body>
<div id="wrapper">
<div id="main_container">
<div id="left_column">
<p>I have two divs inside of a container. One on the left, one on the right, side by side. How am I able to make each one be of equal height, even though they have different content.</p>
</div><!-- LEFT COLUMN -->
<div id="right_column">
<p>I have two divs inside of a container. One on the left, one on the right, side by side. How am I able to make each one be of equal height, even though they have different content.</p>
<p> </p>
<p>For example, the right div has a lot of content, and is double the height of the left div, how do I make the left div stretch to the same height of the right div?</p>
<p> </p>
<p>Is there some JavaScript (jQuery) code to accomplish this?</p>
</div><!-- RIGHT COLUMN -->
</div><!-- MAIN CONTAINER -->
</div><!-- WRAPPER -->
</body>
</html>
This is what it looks like:
you can get it working with js:
<script>
$(document).ready(function() {
var height = Math.max($("#left").height(), $("#right").height());
$("#left").height(height);
$("#right").height(height);
});
</script>
I've seen many attempts to do this, though none met my OCD needs. You might need to dedicate a second to get your head around this, though it is better than using JavaScript.
Known downsides:
Does not support multiple element rows in case of a container with dynamic width.
Does not work in IE6.
The base:
red is (auxiliary) container that you would use to set margin to the content.
green is position: relative; overflow: hidden and (optionally, if you want columns to be centered) text-align: center; font-size: 0; line-height: 0;
blue display: block; float: left; or (optionally, if you want columns to be centered) display: inline-block; vertical-align: top;
So far nothing out of ordinary. Whatever content that blue element has, you need to add an absolutely positioned element (yellow; note that the z-index of this element must be lower than the actual content of the blue box) with this element and set top: 0; bottom: 0; (don't set left or right position).
All your elements now have equal height. For most of the layouts, this is already sufficient. My scenario required to have dynamic content followed by a static content, where static content must be on the same line.
To achieve this, you need to add padding-bottom (dark green) eq to the fixed height content to the blue elements.
Then within the yellow elements create another absolutely positioned (left: 0; bottom: 0;) element (dark blue).
Supposedly, if these boxes (yellow) had to be active hyperlinks and you had any style that you wanted to apply to the original blue boxes, you'd use adjacent sibling selector:
yellow:hover + blue {}
Here is a the code and demo:
HTML:
<div id="products">
<ul>
<li class="product a">
<a href="">
<p class="name">Ordinary product description.</p>
<div class="icon-product"></div>
</a>
<p class="name">Ordinary product description.</p>
</li>
<li class="product b">
<a href="">
<p class="name">That lenghty product description or whatever else that does not allow you have fixed height for these elements.</p>
<div class="icon-product"></div>
</a>
<p class="name">That lenghty product description or whatever else that does not allow you have fixed height for these elements.</p>
</li>
<li class="product c">
<a href="">
<p class="name">Another ordinary product description.</p>
<div class="icon-product"></div>
</a>
<p class="name">Another ordinary product description.</p>
</li>
</ul>
</div>
SCSS/LESS:
#products {
ul { position: relative; overflow: hidden; text-align: center; font-size: 0; line-height: 0; padding: 0; margin: 0;
li { display: inline-block; vertical-align: top; width: 130px; padding: 0 0 130px 0; margin: 0; }
}
li {
a { display: block; position: absolute; width: 130px; background: rgba(255,0,0,.5); z-index: 3; top: 0; bottom: 0;
.icon-product { background: #ccc; width: 90px; height: 90px; position: absolute; left: 20px; bottom: 20px; }
.name { opacity: 1; }
}
.name { position: relative; margin: 20px 10px 0; font-size: 14px; line-height: 18px; opacity: 0; }
a:hover {
background: #ddd; text-decoration: none;
.icon-product { background: #333; }
}
}
}
Note, that the demo is using a workaround that involves data-duplication to fix z-index. Alternatively, you could use pointer-events: none and whatever solution for IE.
here is very simple solution with a short css display:table
<div id="main" class="_dt-no-rows">
<div id="aside" contenteditable="true">
Aside
<br>
Here's the aside content
</div>
<div id="content" contenteditable="true">
Content
<br>
geht's pellentesque wurscht elementum semper tellus s'guelt Pfourtz !. gal hopla
<br>
TIP : Just clic on this block to add/remove some text
</div>
</div>
here is css
#main {
display: table;
width: 100%;
}
#aside, #content {
display: table-cell;
padding: 5px;
}
#aside {
background: none repeat scroll 0 0 #333333;
width: 250px;
}
#content {
background: none repeat scroll 0 0 #E69B00;
}
its look like this
Well, I don't do a ton of jQuery, but in the CSS/Javascript world I would just use the object model and write a statement as follows:
if(leftDiv.style.height > rightDive.style.height)
rightDiv.style.height = leftDiv.style.height;
else
leftDiv.style.height = rightDiv.style.height)
There's also a jQuery plugin called equalHeights that I've used with some success.
I'm not sure if the one I'm using is the one from the filament group mentioned above, or if it's this one that was the first google result... Either way a jquery plugin is probably the easiest, most flexible way to go.
Use this in jquery document ready function. Considering there are two divs having ids "left" and "right."
var heightR = $("#right").height();
var heightL = $("#left").height();
if(heightL > heightR){
$("#right").css({ height: heightL});
} else {
$("#left").css({ height: heightR});
}
Although many disagree with using javascript for this type of thing, here is a method that I used to acheive this using javascript alone:
var rightHeight = document.getElementById('right').clientHeight;
var leftHeight = document.getElementById('left').clientHeight;
if (leftHeight > rightHeight) {
document.getElementById('right').style.height=leftHeight+'px';
} else {
document.getElementById('left').style.height=rightHeight+'px';
}
With "left" and "right" being the id's of the two div tags.
This is what I use in plain javascript:
Seems long, but is very uncomplicated!
function equalizeHeights(elements){
//elements as array of elements (obtain like this: [document.getElementById("domElementId"),document.getElementById("anotherDomElementId")]
var heights = [];
for (var i=0;i<elements.length;i++){
heights.push(getElementHeight(elements[i],true));
}
var maxHeight = heights[biggestElementIndex(heights)];
for (var i=0;i<elements.length;i++){
setElementHeight(elements[i],maxHeight,true);
}
}
function getElementHeight(element, isTotalHeight){
// isTotalHeight triggers offsetHeight
//The offsetHeight property is similar to the clientHeight property, but it returns the height including the padding, scrollBar and the border.
//http://stackoverflow.com/questions/15615552/get-div-height-with-plain-javascript
{
isTotalHeight = typeof isTotalHeight !== 'undefined' ? isTotalHeight : true;
}
if (isTotalHeight){
return element.offsetHeight;
}else{
return element.clientHeight;
}
}
function setElementHeight(element,pixelHeight, setAsMinimumHeight){
//setAsMinimumHeight: is set, we define the minimum height, so it can still become higher if things change...
{
setAsMinimumHeight = typeof setAsMinimumHeight !== 'undefined' ? setAsMinimumHeight : false;
}
var heightStr = "" + pixelHeight + "px";
if (setAsMinimumHeight){
element.style.minHeight = heightStr; // pixels
}else{
element.style.height = heightStr; // pixels
}
}
function biggestElementIndex(arr){
//http://stackoverflow.com/questions/11301438/return-index-of-greatest-value-in-an-array
var max = arr[0];
var maxIndex = 0;
for (var i = 1; i < arr.length; i++) {
if (arr[i] > max) {
maxIndex = i;
max = arr[i];
}
}
return maxIndex;
}
I agree with initial answer but the JS solution with equal_heights() method does not work in some situations, imagine you have products next to each other. If you were to apply it only to the parent container yes they will be same height but the product name sections might differ if one does not fit to two line, this is where i would suggest using below
https://jsfiddle.net/0hdtLfy5/3/
function make_children_same_height(element_parent, child_elements) {
for (i = 0; i < child_elements.length; i++) {
var tallest = 0;
var an_element = child_elements[i];
$(element_parent).children(an_element).each(function() {
// using outer height since that includes the border and padding
if(tallest < $(this).outerHeight() ){
tallest = $(this).outerHeight();
}
});
tallest = tallest+1; // some weird shit going on with half a pixel or something in FF and IE9, no time to figure out now, sowwy, hence adding 1 px
$(element_parent).children(an_element).each(function() {
$(this).css('min-height',tallest+'px');
});
}
}

Categories

Resources