I want to change the height of div when I scroll
#H {
position: fixed;
height: 200px;
background: red;
width: 200px
}
<div style="height:2000px; position:relative">
<div id="H"></div>
</div>
<script type="text/javascript">
window.onscroll = function() {
myFunction()
};
function myFunction() {
VAR X = document.getElementById("H");
if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
X.css("height": "100px");
} else {
X.css("height": "200px");
}
}
</script>
But the code is not working. In the above code I tried to change the height of the div with id="H" on scroll from 200, that I have mentioned in the CSS to 100, but the JS is not running.
You have some problem in JavaScript.
Change it to like:
<script>
window.onscroll = function() {myFunction()};
function myFunction() {
var X=document.getElementById("H");
if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
X.style.height = "1000px";
}
else {
X.style.height = "200px";
}
}
</script>
VAR X should be var X
And
X.css("height":"1000px"); change style like X.style.height = "1000px";
Working Fiddle
there are a few javascript errors in your code.
VAR X=document...
"var" has to be lower case, not upper case.
X.css(...)
"css" is not a function. Use X.style.height instead.
Generally look into how to debug javascript code. A good browser is your friend with this (e.g. Firefox or Chrome). Use console.log("foo"); to print a message or a variable to the browsers console to see what happens in your code. You can also use step by step debugging.
If you use the JavaScript console in your browser, you can see that document.getElementById("H").css is not a function.
Instead use for example document.getElementById("H").style.height = "300px";
CSS is not directly accessible in JavaScript unless you use getComputedStyle API, however the class can be accessed using element.className and changed as long as you have the relevant class already created.
element.style.property is how you change inline styles. There is a big difference in both, in that one is part of the DOM structure while the other is connected to the DOM via a class name and the stylesheet.
Specific to you question:
Here is the fiddle
window.onscroll = function() {myFunction()}; is simply window.onscroll = myFunction it is the same and more idiomatic.
Related
I have a div id="coding" set on height:300px on CSS.
when I click another div id="menu", I want #coding to change it's height to 800px. I managed to do that like this
<script>
function changec() {
document.getElementById('coding').style.height = "800px";
}
</script>
Now, when click the #menu again, I want the height to get back to it's original 300px value. Can someone help? The code is:
HTML
<div id="coding">
<div id="menu" onclick="changec()">≡</div>
...
</div>
CSS
#coding{
...
height:300px;
}
Simple check if the value is set - remove it (then CSS height will take over).
function changec() {
var xDiv = document.getElementById('coding');
if (xDiv.style.height == '')
xDiv.style.height = '800px'
else
xDiv.style.height = ''
}
Demo: http://jsfiddle.net/ygalanter/BLE6N/
one of the solution for your problem is as follows:
First count how many times you click on #menu
now depending on your expectation you can change the javascript as follows
<script type="text/javascript">
var count = 0;
function changec() {
count++;
if(count%2==1)
document.getElementById("coding").style.height = "800px";
else
document.getElementById("coding").style.height = "300px";
}
</script>
Another alternative solution is
<script type="text/javascript">
function changec() {
var currentheight = document.getElementById('coding').clientHeight;
if (currentheight == 300)
document.getElementById('coding').style.height = "800px";
else if (currentheight == 800)
document.getElementById('coding').style.height = "300px";
}
</script>
Not sure why you tagged jQuery since you didn't use it, but still...Considering the possibility that you are willing to use/learn it, I created a jsFiddle for it: http://jsfiddle.net/Tm2Hd/.
CSS:
#coding{
border:1px solid black; /*optional: Keep track of your div's expand*/
height:300px;
}
#coding.larger{
height:800px;
}
JS:
function changeHeight() {
if($('#coding.larger').length>0)
{
$('#coding').removeClass("larger");
}
else
{
$('#coding').addClass("larger");
}
}
HTML
<div id="coding">
<!--<div onclick="changeHeight()">≡</div>
Personally, I don't suggest using divs as clickable objects... Why don't you use buttons instead?
-->
<button onclick="changeHeight()">≡</button>
...
</div>
My solution to your problem is: Create a new class named larger, pointing to your div, and toggle between this and the original whenever you click the button.
function show()
{
var elem = document.getElementById("pop").querySelector('li:nth-child(3)');
elem.style.width = "500px";
}
</script>
I have this code attached to an onclick
<li onclick="show()">
The element is originally 200px and then turns into 500px when clicked. How do I make it work so that when I click it again it goes back to 200??
The best thing to do would be to use a CSS class to set the width. This has the advantage that:
You don't have to specify the width in multiple places (CSS and JS) (-> easier to maintain)
You don't have to know the default width of the element (-> more flexible)
Example:
CSS:
.wide {
width: 500px;
}
HTML:
<li onclick="show(this)">...</li>
JS:
function show(elem) {
elem.classList.toggle('wide');
}
DEMO
Have a look at the MDN documentation regarding classList for information about browser support. You can also find alternatives in this excellent question/answer about handling CSS classes on elements: Change an element's class with JavaScript
To learn more about event handling (ways to bind event handlers, information available inside event handlers, etc), have a look at the excellent articles at quirksmode.org.
function show() {
var elem = document.getElementById("pop").querySelector('li:nth-child(3)'),
width = parseInt(elem.style.width, 10);
if (width === 500) {
elem.style.width = "200px";
}
else {
elem.style.width = "500px";
}
}
Although, I'd probably name the function toggle or something similar and not inline the click handler.
Use a control variable
var clickControl = false;
function show()
{
if(clickControl)
{
var elem = document.getElementById("pop").querySelector('li:nth-child(3)');
elem.style.width = "500px";
clickControl = !clickControl;
}
else
{
var elem = document.getElementById("pop").querySelector('li:nth-child(3)');
elem.style.width = "200px";
clickControl = !clickControl;
}
}
I made a menu on html (on the side and 100% heigth, expandeable as in android holo)
<div id="menu">
<button class="menubutton"></button>
<button class="menubutton"></button>
</div>
The menu normally remains transparent and with a short width:
#menu {
background-color: transparent;
width: 8%;
}
The idea was to expand and color it on hover. It was easy:
#menu:hover {
background-color: blue;
width: 90%;
}
There is no problem untill here. I need the same effect on focus. There is no way in css to change parent css on child focus (neither hover by the way, but it is not needed, cuase i can use the entire menu hover).
So i used a script:
var menubuttonfocus = document.getElementsByClassName("menubutton");
for (i=0; i<menubuttonfocus.length; i++) {
menubuttonfocus[i].addEventListener("focus", function() {
menu.style.backgroundColor = "blue";
menu.style.width = "90%";
});
menubuttonfocus[i].addEventListener("blur", function() {
menu.style.backgroundColor = "transparent";
menu.style.width = "8%";
});
}
The script works just fine, the problem is that when you trigger those events by focusing a button, the css of #menu:hover changes somehow and #menu does not change when hovering. I tried to solve this by doing something similar but with hover instead of focus:
menu.addEventListener("mouseenter", function(){
menu.style.backgroundColor = "blue";
menu.style.width = "90%";
});
menu.addEventListener("mouseout", function(){
menu.style.backgroundColor = "transparent";
menu.style.width = "8%";
});
This works somehow, but it is REALLY buggy.
I tried also to select "#menu:hover,#menu:focus", but it doesn't work because the focus is on the button elements and not in #menu.
Please avoid jquery if posible, and i know it's asking for too much but a pure css solution would be awesome.
Probably helpful info: html element are created dinamically with javascript.
I can show more code or screenshot, you can even download it (it is a chrome app) if needed: chrome webstore page
Thanks.
SOLVED: I did what #GCyrillus told me, changing #menu class on focus via javascript eventListener. .buttonbeingfocused contains the same css as "#menu:hover". Here is the script:
var menubuttonfocus = document.getElementsByClassName("menubutton");
for (i=0; i<menubuttonfocus.length; i++) {
menubuttonfocus[i].addEventListener("focus", function() {
menu.classList.add("buttonbeingfocused");
});
menubuttonfocus[i].addEventListener("blur", function() {
menu.classList.remove("buttonbeingfocused");
});
}
if the problem is what I think it is - you forgetting about one thing:
When you focusing / mouseentering the .menubutton - you are mouseleaving #menu and vice-versa - so your menu behaviour is unpredictible because you want to show your menu and hide it at the same time.
solution is usually setting some timeout before running "hiding" part of the script, and clearing this timeout (if exist) when running "showing" part.
it will be something like this:
var menuTimeout;
function showMenu() {
if (menuTimeout) clearTimeout(menuTimeout);
menu.style.backgroundColor = "blue";
menu.style.width = "90%";
}
function hideMenu() {
menuTimeout = setTimeout( function() {
menu.style.backgroundColor = "transparent";
menu.style.width = "8%";
}, 800);
}
//then add your listeners like you did - but put these functions as a handlers - like this:
menu.addEventListener("mouseenter", showMenu);
...
//in addition you need also "mouseenter" and "mouseleave" events handled on .menubuttons
This is my Javascript:
<script type="text/javascript">
function contactChange() {
var contact = document.getElementbyId("contact");
if (contact.style.display == "none") {
contact.style.display = "block";
} else {
contact.style.display = "none";
}
}
</script>
And here is my site:
http://www.andrewjalexander.com/
It's document.getElementById, not document.getElementbyId. (In JS, name of variables and functions are case-sensitive)
Debugging tip : Look at the JS console (F12 in Google Chrome and IE9, Ctrl+Shift+K in Firefox). In this case, following error can be seen:
It shows where the error happened (line 260 in your HTML/JS code) and what the error is(Object #<HTMLDocument> has no method getElementbyId).
It's getElementById, not getElementbyId. Note the upper case "B".
You're going to hate yourself for this, but you put getElementbyId() instead of getElementById(). Note the capitalized "B" in the second version.
Its getElementById in place of getElementbyId
Try to hide then show a element on scroll I had to go this route. Basically i tried to use window so I used 'body'
$(document).ready(function() {
$('body').scroll(function() {
var scroll = $('body').scrollTop();
if (scroll <= 50 ) {
console.log(scroll);
we
} else {
$("#label").css('fill', 'none');
$(".label").addClass(".transition");
}
if (scroll <= 150) {
$(".sizeLG").css('color', '#ffffff');
} else {
$(".sizeLG").css('color', '#00000000');
$(".sizeLG").addClass(".transition");
}
});
});
Make sure your id or class you used in html code will accordingly .(dot) Or #(hash) with their name.
Ex:
For id:
html:
<div id= idName>
****Some code****
<\div>
Javascript:
var VariableName = document.querySelector( "#idName");
Or
var VariableName = document.getElementById( "#idName");
For class:
html:
<div id= className>
****Some code****
<\div>
Javascript
var VariableName = document.querySelector( ".className");
Or
var VariableName = document.getElementById( ".className");
I have 2 divs, one positioned absolutely right: 0 and the other relatively positioned center screen. When the window's width is too small, they overlap. How can I invoke a javascript function when this happens?
Thanks.
Mike
Edited to make clearer.
To check for overlapping div's you might wanna do a check once the page is loaded, and whenever the window is resized:
window.onload = checkOverlap;
window.onresize = checkOverlap;
And then use some offset-checking:
function checkOverlap() {
var centerBox = document.getElementById('centerDiv');
var rightBox = document.getElementById('rightDiv');
console.log("centerbox offset left: " + centerBox.offsetLeft);
console.log("centerbox width: " + centerBox.offsetWidth);
console.log("rightbox offset left: " + rightBox.offsetLeft);
if ((centerBox.offsetLeft + centerBox.offsetWidth) >= rightBox.offsetLeft) {
centerBox.style.display = "inline-block";
} else {
centerBox.style.display = "block";
}
}
You might wanna do some more checks in the function, e.g. to see if the box is already displayed inline, and such. But that should give you a good place to start.
edit: added some diagnostics and fixed error
Part 1:
Do it like this:
<script type="text/javascript">
document.getElementById('example').style.display = "inline";
</script>
...
<div id="example"> ... </div>
document.getElementById('div_id').style.display = 'inline-block'
document.getElementById('div_id').offsetWidth gives us width of div
offsetHeight, offsetLeft, offsetTop are useful also.