Hello I want to make a Menu thats pops out of the side when I click a button. I have it all set up with the CSS but the Javascript part doesn't work.
I want to test if the width of menubarWrapper is equal to 300 then the width of the menubarWrapper needs to change to 0px and if it isn't equal to 300px than change it to 300px.
I have the following JS:
function menuBarToggle() {
var menuWrapper = document.getElementById('menuWrapper');
if menuWrapper.width == 300 {
menuWrapper.style.width = "0";
} else {
menuWrapper.style.width = "300";
}
}
I also tried in the IF statement menuWrapper.style.width but that doesn't work also
There are other answers that are just fine --
use "300px", not "300"
Surround your conditional with a parentheses.
(You'll need both, by the way.)
But I wanted to make sure that somewhere on this page, someone pointed out that this is a very brittle way of toggling. You have a magical, hardcoded integer for the size, which might break if you ever wanted to style things differently. And if you decide one day to fade out the menu, then the test won't work at all.
Might I suggest that, instead, you create two classes in CSS:
.menu-item { width: 300px; }
.menu-item.collapsed { width: 0; }
And then in javascript, you'll only have to write the following:
function menuBarToggle() {
var menuWrapper = document.getElementById('menuWrapper');
menuWrapper.classList.toggle('collapsed');
}
Not only is the intention easier to read, but this will allow you to swap out the behavior if you decide that, instead of purely narrowing the menu, you might want it to fade out, or animate it to the left, or... well... whatever can come up with.
Your script has a typo. Add '()' for an if statement.
function menuBarToggle() {
var menuWrapper = document.getElementById('menuWrapper');
if (menuWrapper.width == 300) {
menuWrapper.style.width = "0";
} else {
menuWrapper.style.width = "300";
}
}
When changing the width of an element via style.width, you have to append px to the end of the string:
function menuBarToggle() {
var menuWrapper = document.getElementById('menuWrapper');
if menuWrapper.width == 300 {
menuWrapper.style.width = "0px";
} else {
menuWrapper.style.width = "300px";
}
}
Related
I'm still developing a genius forum for my website. I want to add some fancy javascript effects. I don't want to use jQuery for now.
My problem is the following: I have an element which appears by checking if the value of the function is true or false. With those check my article shows or hides.
My question is: Is it possible to use transitions so that my block drops down like the way transitions do?
The first js function describes the check and the next function hides or show my article when the values are not empty.
function CheckEmptyValues() {
var inputFields = document.getElementsByTagName('input');
var textFields = document.getElementsByTagName('textarea');
var postData = [inputFields, textFields];
for(var i=0; i<postData.length; i++) {
for(var j=0; j<postData[i].length; j++) {
if(postData[i][j].value !== '') {
return false;
}
}
}
return true;
}
function showPreview() {
if (CheckEmptyValues() === false) {
this.prevPost.style.display = "block";
}
else {
this.prevPost.style.display = "none";
}
}
When my emptyvalues are false the article appears and if not, it disappears. But when this happens you see only show or hide, no further effect or something.
I want to make this something like this effect: http://www.w3schools.com/css/tryit.asp?filename=trycss3_transition1
The height value should start with 0 and end with 150 height or something like that.
Does anyone have a solution how to make this look cool?
Thanks in advance.
No, you can't, display is defined as non animatable.
If you want workarounds, see CSS3 Animation and Display None.
No, display doesn't come in transition-property. But, you can try opacity and for the display:block , put it in your div:hover or only div css.
You could use opacity, and set it to 0 or 1:
this.prevPost.style.display = "block";
this.prevPost.style.opacity = 1;
Basically I have this header that slides out of the way when people don't want it anymore and can be slid down again when they want it. I want it to be down by default however I don't want people to have to constantly click the header toggle every-time a new page loads. I have read about using cookies but my skill in javascript is rather limited. Here is the code I currently use that works well:
<div id="headtoggle" onclick="headertoggle()"></div>
<script>
function headertoggle() {
var top;
var pagetop;
if (document.getElementById("page-header").style.top === "-210px") {
top = "-11px";
pagetop = "275px";
} else {
top = "-210px";
pagetop = "80px";
}
document.getElementById("page-header").style.top = top;
document.getElementById("page-body").style.top = pagetop;
}
</script>
How do I change the code so that it "remembers" what the last setting was for each person? I am willing to also use jquery. Any help for this very novice coder would be more than appreciated.
Thanks,
Dylan
EDIT2: I changed the code given to me a bit and am having a new problem.
<div id="headtoggle" onclick="headertoggle()" onload="topposition()"></div>
<script>
function topposition() {
var top;
var pagetop;
if (localStorage.getItem("headerDown") == "false") {
top = "-11px";
pagetop = "275px";
} else {
top = "-210px";
pagetop = "80px";
}
document.getElementById("page-header").style.top = top;
document.getElementById("page-body").style.top = pagetop;
}
</script>
<script>
function headertoggle() {
var top;
var pagetop;
if (document.getElementById("page-header").style.top === "-210px") {
localStorage.setItem("headerDown", false);
top = "-11px";
pagetop = "275px";
} else {
localStorage.setItem("headerDown", true);
top = "-210px";
pagetop = "80px";
}
document.getElementById("page-header").style.top = top;
document.getElementById("page-body").style.top = pagetop;
}
</script>
The toggle works as intended however whenever I fire "function topposition ()" in the firefox console I get the following error:
SyntaxError: expected expression, got end of script data:,/*
EXPRESSION EVALUATED USING THE FIREBUG COMMAND LINE:
*/%0A%09function%20topposition() Line 2
You can create a cookie by using
document.cookie="headerDown=true";
Then when the header is moved up overwrite the cookie with the same code changed to false.
If you then add some code that reads the cookies on page load you will be able to determine what is need.
You can read cookies by accessing document.cookie which will be a string of any cookies available in the following format.
cookie1=value; cookie2=value; cookie3=value;
Look for your cookie and you should be able to set whether the header is up or down from there.
i would say local storage would be a good option for this. Just log an event or variable or whatever and then check for it each time you load the page.
https://developer.mozilla.org/en-US/docs/Web/API/Window.localStorage
Using local storage will allow you to save variables between page loads.
add localStorage.setItem(name,value) in to your if statements as below.
If you are only using the headerToggle function to position these elements then the if statement below the function should suffice. It requires two calls to the headertoggle function in the even that you want the header to be down.
You will need to make sure the if statement is placed after the html for the divs, most likely best place is the very bottom of the page.
function headertoggle() {
var top;
var pagetop;
if (document.getElementById("page-header").style.top === "-210px") {
localStorage.setItem("headerDown", true);
top = "-11px";
pagetop = "275px";
} else {
localStorage.setItem("headerDown", false);
top = "-210px";
pagetop = "80px";
}
document.getElementById("page-header").style.top = top;
document.getElementById("page-body").style.top = pagetop;
}
if (localStorage.getItem("headerDown") == "true") {
headertoggle();
}
headertoggle();
I'm having toruble with this function, it requires two clicks before the if statement is satisfied even though in the CSS the condition should be met. On the fist click, the console shows triggered but not if state on the second click it does show if state can anyone understand why the condition is not being met?
function searchShow() {
console.log('started');
document.getElementById('top_line_2a').addEventListener('click', function() {
console.log('triggered')
var searchClickIcon = document.getElementById('top_line_2a');
var searchClick = document.getElementById('top_line_3');
if(searchClick.style.height == '0em') {
console.log('if state');
//searchClick.style.display = 'block';
searchClick.style.height = '3em';
searchClickIcon.style.color = 'white';
searchClickIcon.style.textShadow = '0px 0px 7px white';
document.getElementsByClassName('search')[0].focus();
} else {
//searchClick.style.display = 'none';
searchClick.style.height = '0em';
searchClickIcon.style.color = 'rgba(255, 187, 61, 1)';
searchClickIcon.style.textShadow = '';
}
})
console.log('added');
}
When implementing ping-pong / toggle effects, try not to compare with attribute value directly. The zero height could be "0em", "0", or numeric 0. You could try normalizing the value for this one particular case:
if (parseInt(searchClick.style.height,10)==0) {
// show the container
} else {
// hide the container
}
A much more reliable way is to take advantage of the fact that every DOM element can be dynamically assigned new attributes. Since you already have a handle to the searchClick object:
if (searchClick.showing){
searchClick.showing=null;
// hide the container
} else {
searchClick.showing=true;
// show the container
}
"showing" is your own attribute. When you first click on it, the marker is not there, so it'll show the container (initially hidden). Then the showing flag is attached to it, so you can detect it in the next click. If your initial state is showing, then use a different flag to reverse the logic. This is a sure fire method to implement a toggle.
You shouldn't be using the height. Use a variable instead.
var triggered = false;
function searchShow() {
document.getElementById('top_line_2a').addEventListener('click', function() {
//Do stuff
if(!triggered) {
triggered = true;
//Do stuff
} else {
triggered = false;
//Do stuff
}
})
}
Checking for a style in an if statement isn't a good practice. If you ever change the size of your container for X reason, you'll also have to change the if/else statement to fit the change. It also make the code that much less clear to whoever will read it. Always try to avoid using hardcoded numbers when you can use something more effective.
I am working on homework that involves working with javascript. Part of my homework assignment is to use the event handlers onmouseout and onmouseouver. What is supposed to happen when the user hovers over a specific div element, the font size grows by 25%, and when the user mouses out of the div element, the font size goes back to normal. My question is, is it possible to incorporate both an onmouseover function and an onmouseout function into one function? Somehow that is what my teacher wants us to do. I have this started so far.
function FontSize(x)
{
x.style.fonstSize = large;
}
I'm also thinking this isnt the correct code to make the font 25% larger, but I'm not sure how to really incorporate an onmouseout in this function.
As a teacher myself, I am 99% sure that by "one function" the instructor means one general-purpose function to change the font size, not one function which uses conditional statements to work backwards and figure out whether it should be doing onmouseout or onmouseover.
Your script should contain:
function resize(elem, percent) { elem.style.fontSize = percent; }
Your HTML should contain:
<div onmouseover="resize(this, '125%')" onmouseout="resize(this, '100%')"
Text within div..
</div>
Note: Situations such as here, are exactly why JavaScript has the keyword "this"--to save us from needing to use complicated document.getElementById() statements.
You can use "%" property for controlling font-size as described here with the following code.
document.getElementById("div1").onmouseover = function() {
document.getElementById("div1").style.fontSize = "125%"
};
document.getElementById("div1").onmouseout = function() {
document.getElementById("div1").style.fontSize = "100%";
};
Here is the working jsfiddle : http://jsfiddle.net/LxhdU/
Yes you can. Call the same function on both events, and pass a parameter to indicate whether the fontsize should increase or decrease.
ChangeFontSize = function(element, shouldIncreaseFontsize)
{
var small=14;
var large = small * 1.25;
if(shouldIncreaseFontsize) {
element.style.fontSize = large + "px";
}
else {
element.style.fontSize = small + "px";
}
}
http://jsfiddle.net/TMHbW/1/
I'd do something simple like the following. The large and small values can be whatever you need them to be for the font size to work or they can be variables you've defined in prior code.
Demo: http://jsfiddle.net/lucuma/EAbYn/
function doHover(e) {
if (e.type=='mouseover') {
this.style.fontSize = "large";
} else {
this.style.fontSize = "small";
}
}
var el = document.getElementById('myelement')
el.onmouseout =doHover;
el.onmouseover=doHover;
It is possible you do not need to call both the events on the element explicitly instead extension you create will do that.Extend the Element's prototype. Jquery also does similar to this.
Ref Prototype
See Fiddle:- http://jsfiddle.net/4fs7V/
Element.prototype.hover= function( fnOver, fnOut ) {
this.onmouseover=fnOver;
this.onmouseout=fnOut || fnOver;
return this;
};
document.getElementById('test').hover(function(){
//do your mouseover stuff
},
function(){
//do your mouseout stuff
});
Update
Same can be achieved with just one function too:-
Hover me
.largeFont {
font-size:125%;
}
Element.prototype.hover = function (fnOver, fnOut) {
this.onmouseover = fnOver;
this.onmouseout = fnOut || fnOver;
return this;
};
document.getElementById('test').hover(changeMe);
function changeMe()
{
if(this.hasAttribute('class'))
{
this.removeAttribute('class');
}
else
{
this.setAttribute('class', 'largeFont');
}
}
I decided to improve my JavaScript skills by practicing with some often used modules.
I am creating a fixed feedback button that comes up when you press it and goes down when you press again. Everything works, but I want it to be animated.
I used this code to get it done
function rollUp(item){
if(item.className == "on") {
item.className="off";
document.getElementById("container").style.top = "97%";
} else {
item.className="on";
document.getElementById("container").style.top = "78.5%";
}
}
Now I just don't get those percentages animated, I found many descriptions about animating divs by px, but I don't get this working.
So the div has to be moved from top position 97% to 78.5%
Any help?
Are you using jQuery? If yea, please try this:
function rollUp(item){
if(item.className == "on") {
item.className="off";
$("#container").animate({top: "97%"});
} else {
item.className="on";
$("#container").animate({top: "78.5%"});
}
}
You would need something like a timeout which will change the position in small steps which actually is "animation", here
function rollUp(){
var ph=document.getElementById("container").style.top.toString();
ph.replace("px","");
var phi=parseInt(ph);
if(phi<800){
if(item.className == "on") {
item.className="off";
document.getElementById("container").style.top = (phi+10).toString()+"px";
} else {
item.className="on";
document.getElementById("container").style.top = "600px";
}
Window.setTimeout(roolUp(), 300);
}
}