Javascript to make a button take multiple action on an element - javascript

I currently have buttons that adjust the height, color, opacity of a box for example-
document.getelementbyID("growbutton").addEventlistener("click", function growFunction() {
document.getelementbyID("box").style.height = "300px"
});
document.getelementbyID("bluebutton").addEventlistener("click", function blueFunction() {
document.getelementbyID("box").style.color = "#0000FF"
});
Those work fine- What I want is a reset button, that will reset "box" back to original settings. Current JS looks like this.
document.getelementbyID("resetbutton").addEventlistener("click", function resetFunction() {
document.getelementbyID("box").style.height = "150px"
});
document.getelementbyID("resetbutton").addEventlistener("click", function resetFunction() {
document.getelementbyID("box").style.color = "#FFA500"
});
When executed however, the "box" only resets in height, but does not reset in color. Any help would be greatly appreciated.

You don't need to send a single action per function. You can create a function resetFunction and pass it to addEventListener.
function resetFunction(){
let box = document.getElementById("box");
box.style.height = "150px";
box.style.color = "#FFA500";
}
document.getElementById("resetbutton").addEventlistener("click", resetFunction);
This is the best way, but probably changing the name of your second function to resetFunction2 would also work

In effect you'll need to store a set of default values that you can refer to.
You can do this when the document loads, ie:
<head>
<script>
var defaults = {}
function setDefaults() {
defaults.box = {
height: document.getElementByID("box").style.height,
color: document.getElementByID("box").style.color
}
// I tucked these functions in here since they need to fire after the page loads
document.getElementByID("resetbutton").addEventListener("click", function resetFunction() {
document.getElementByID("box").style.height = defaults.box.height
document.getElementByID("box").style.color = defaults.box.color
});
}
</head>
<body onload='setDefaults()'>
...

Ya'll are going to be really mad at me... Super noob mistake. The reset function would've been working this whole time with all of the JS that was posted. My color change button address backgroundcolor, my reset addresses color. It's fixed now!

Related

Retaining scrollbar position using jquery

I have a java function,
private GroupsSelector group(LabourInputReportCriteria.Level level) {
HtmlSelectBooleanCheckbox box = new HtmlSelectBooleanCheckbox();
boolean isSelected = selections.isGroupSelected(level);
box.setSelected(isSelected);
// box.setDisabled(isDaySelectedOnFirst(level));
String id="groupBy" + level.getClass().getSimpleName();
box.setId(id);
box.setOnclick("submit()");
box.addValueChangeListener(u.addExpressionValueChangeListener("#{reportSearchCriteriaModel.groupBy}"));
HtmlOutputText labelComponent = new HtmlOutputText();
labelComponent.setValue(getGroupSelectionValue(level));
tr().td();
html(box);
html(" ");
html(labelComponent);
//html("<span id='"+id+ "'></span>");
//html("<script> function resetGroupsSelector() { var x = document.getElementById('search_report_form:groupByWeekLevel'); alert(x); } </script>");
endTd().endTr();
return this;
}
Whenever I click on a checkbox, sumbit() is called and it has some functionality at the backend. Now, my question is whenever I click on a checkbox, the scrollbar position is moving up i.e, it is going on top of the page. I want to avoid this. I want to retain my scrollbar position as it is. How am I supposed to do it?
I tried adding the follwing code but it dint work.
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" >
var addTweet = function() {
var scrollPosition = $(document).scrollTop();
$('#results9016').prepend($newTweet);
$('html, body').scrollTop(scrollPosition);
}
</script>
Please help.
inside the function that you call when clicking you can say
function submit(event) {
event.preventDefault();
...
}

onmouseover function Javascript for changing the background of a section

I was trying to write a function that changes the color of background of a section by going over it with the mouse - using 'onmouseover'. I was looking for similar question and tried the solutions that was offered but it did not work on my code.
Here is what i did:
function Rectangle(count){
var newRec = document.createElement("SECTION");
newRec.style.width="202px";
newRec.style.height="312px";
newRec.style.border="1px solid #3f3f3f";
newRec.style.background = "#FFFFFF";
newRec.style.display = "inline-block";
newRec.style.margin= "44px";
newRec.style.size= "50px";
var appendRec = function() {
document.addEventListener("onmouseover", myFunction);
document.getElementsByTagName('main')[0].appendChild(newRec);
};
function myFunction() {
document.getElementTagName("SECTION").style.background = "#000000";
};
appendRec();
};
Can anyone tell me what i did wrong?
And I was trying to work with the console but this code doesn't say anything is wrong...
document.getElementTagName("SECTION").style.background = "#000000"; is wrong.
First, it's called getElementsByTagName(). And second, it returns an array, not just one element.
Solution: Give the <section> an id and use getElementById() instead.
You just need
document.getElementById('WhichElementWillBeHoveredID').onmouseenter = function() {
// when entering element...
}
document.getElementById('WhichElementWillBeHoveredID').onmouseleave = function() {
// when leaving element
}
Sure... you can easily use CSS as well..
SELECTOR:hover { background-color: #444 }
I created a fiddle to change background color and this is the only requirenment then I think it is good
http://jsbin.com/cagawa/edit?html,css,output
#mydiv{
background: #cccccc;
}
#mydiv:hover{
background: #ffdd00;
}
try change
var appendRec = function() {
document.addEventListener("onmouseover", myFunction);
document.getElementsByTagName('main')[0].appendChild(newRec);
};
to
var appendRec = function() {
document.getElementsByTagName('main')[0].appendChild(newRec);
newRec.addEventListener("mouseover", myFunction);
};
I edited littlebit code, try now :)
If im not wrong on line 12:
document.addEventListener("onmouseover", myFunction);
should be replaced by
document.addEventListener("onmouseover",myFunction());

Why won't my article change color on click?

http://jsfiddle.net/#&togetherjs=fB8flQJ3Ef
My article class, download, won't change the background color on click, I'd like it to occur to anything marked with the class="download", but only on the specific one I clicked
Try this:
window.onload = function()
{
var download = document.querySelectorAll(".download");
for(i in download)
{
download[i].onclick = function()
{
this.style.background = "red";
}
}
}
Thing is that you had : dowload[i].style which can't be used inside the event since it will reference outer "i" and as consequence it gives you errors..

setInterval() example from the Javascript Mozilla docs not working in JSFiddle

I copied over Example #2 given in the Mozilla docs about setInterval() (https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval?redirectlocale=en-US&redirectslug=DOM%2Fwindow.setInterval#Example_1.3A_Generic) but the color of the text does not alternate between red and blue in my JSFiddle:
DEMO: http://jsfiddle.net/lpsternotes/JHpt9/
It can't be because I need jQuery or because of the markup, right? I copied it over exactly.
I also wanted to ask for clarification purposes: the reason var nIntervId; is defined as a global variable at the top is so that it can be used in both the changeColor() and stopTextColor() functions, right?
var nIntervId; //global variable
function changeColor() {
nIntervId = setInterval(flashText, 500);
}
function flashText() {
var oElem = document.getElementById("my_box");
oElem.style.color = oElem.style.color == "red" ? "blue" : "red";
}
function stopTextColor() {
clearInterval(nIntervId);
}
In other words, if the code looked like this:
function changeColor() {
var nIntervId = setInterval(flashText, 500);
}
function flashText() {
var oElem = document.getElementById("my_box");
oElem.style.color = oElem.style.color == "red" ? "blue" : "red";
}
function stopTextColor() {
clearInterval(nIntervId); //undefined??
}
Your functions are defined inside another function (which is executed onLoad) (as per the second drop down menu in the JSFiddle options on the left).
This means they are scoped to that function and are not globals.
They are therefore out of scope for your onload="stopTextColor();" attribute.
Just call stopTextColor() in your existing onload handler and not in another one you create with the onload attribute.
Your fiddle works fine. Just change the second drop down menu on the left which says onLoad to No Wrap - in Head option.
You should also have a look at This link to know WHY.

onmouseout and onmouseover

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');
}
}

Categories