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

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.

Related

Javascript to make a button take multiple action on an element

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!

Calling javascript function in html second time

Below is my code for a simple text based game that i am trying to make but i cannot understand why the first time i call my function with a hyperlink 'link1', it works but when i add another link to my html document using javascript, and try to call another function onclick upon that link, it doesn't work. can somebody explain?
var getupvar = document.getElementById("attack");
getupvar.onclick = attack;
function attack() {
$('<p> Some text </p>').insertBefore("#placeHolder");
$('link2').insertBefore("#placeHolder");
}
var link2event = document.getElementById("defend");
link2event.onclick = defend;
function defend() {
alert("working now");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="console">
<p id="startGameMessage"></p>
<div id="gameArea">
<p id="gameMessage">Some Text</p>
link1
<div id="placeHolder"></div>
</div>
</div>
When you link up your attack onclick, the element exists. But because #defend does not exist on the dom when you run var link2event = document.getElementById("defend");, your onclick never gets set.
Instead try:
var getupvar = document.getElementById("attack");
getupvar.onclick = attack;
function attack(){
$('<p> Some text </p>').insertBefore("#placeHolder");
$('link2').insertBefore("#placeHolder");
var link2event = document.getElementById("defend");
link2event.onclick= defend;
}
function defend(){
alert("working now");
}
jsfiddle https://jsfiddle.net/fv9mpbm6/
This will get your code working how you wish. If you don't do so, your code cannot work because the two lines added to the attack() function will be executed when you call the .js file in your html document as a script and not as a function. This means that the method getElementById("defend") will not find anything, because when you initialize the page, you cannot find any element with this id, you create it when you click on the link.
But do note that if you click attack more than once, your code will break because there will be more than one defend element.
When creating dynamic content, never use ids for handlers! Use classes instead
function attack() {
$('link2').insertBefore("#placeHolder");
}
Also, to ensure proper handling for elements that may not exist yet, leverage jquery's on functionality
$('body').on('click', '.defend', function() {
alert("working now")
})
it is simple, just put the two lines of code
var link2event = document.getElementById("defend");
link2event.onclick= defend;
inside the attack() function, at the end,and it works. This is the new attack() function:
function attack(){
$('<p> Some text </p>').insertBefore("#placeHolder");
$('link2').insertBefore("#placeHolder");
var link2event = document.getElementById("defend");
link2event.onclick= defend;}
If you don't do so this code cannot works because these two lines will be executed when you call the .js file in your html document as a script and not as a function. This means that the method getElementById("defend") will not find nothing, because when you initialize the page, you cannot find any element with this id, you create it when you click on the link.
I hope that this helps!
Cheers!
Try this, I am not sure is this what you expect
var getupvar = document.getElementById("attack"), i=0;
getupvar.onclick = attack;
function attack() {
$('<p> Some text </p>').insertBefore("#placeHolder");
$('link2').insertBefore("#placeHolder");
var link2event = document.getElementById("defend"+i);
link2event.onclick = defend;
i++;
}
function defend() {
alert("working now");
}

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..

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

Set onCLick callback inside object?

I have a carousel object, with images and a pager. The problem is I can't set the onClick to the pager. I'm obviously missing something here but I don't know what.
The error when I click in a pager item is:
Uncaught TypeError: Object #<HTMLDivElement> has no method 'scrollCarouselTo'
I set my onclick
carouselDots.on('click',function(){
this.scrollCarouselTo(1,5); // <-- problem lies here, how can i call this method?
});
and the scrollTo method
this.scrollCarouselTo=function(dotIndex, numDots)
{
//H_SCROLL.scrollToElement("#carouselItem"+dotIndex, 300);
H_SCROLL.scrollToPage(dotIndex, 0 , 300);
this.highlightCarouselDot(dotIndex, numDots);
}
Last, on my HTML file this is how I set it:
var tempCarousel = new Carousel();
tempCarousel.initialize(params,cont,scrollContainer);
My Carousel class: (parts of it that i think are relevant)
function Carousel() {
var container;
var pager;
var opt;
var thisCarousel;
//render the correct number of dots and highlight the indexed one
this.highlightCarouselDot=function(dotIndex, numDots)
{
var ui_str="";
console.log("numDots" + numDots);
for (var i=0;i<numDots;i++)
{
if (i==dotIndex)
ui_str+='<div class="carouselDot selected" id="carouselDot'+i+'"></div>';
else
ui_str+='<div class="carouselDot" id="carouselDot'+i+'"></div>';
}
console.log(ui_str);
console.log(pager);
pager.html(ui_str);
var carouselDots = $(pager.selector + " .carouselDot");
var dotSelected = $(pager.selector + " .selected");
carouselDots.css('background',opt.pagerImage);
carouselDots.width(opt.pagerSize);
carouselDots.height(opt.pagerSize);
carouselDots.on('click',function(){ //replace with touch
this.scrollCarouselTo(0,5);
});
dotSelected.css('background',opt.pagerSelectedImage);
}
this.scrollCarouselTo=function(dotIndex, numDots)
{
//H_SCROLL.scrollToElement("#carouselItem"+dotIndex, 300);
H_SCROLL.scrollToPage(dotIndex, 0 , 300);
this.highlightCarouselDot(dotIndex, numDots);
}
}
Thank you!
You are having trouble understanding where the scope is changing in your code. Yes this refers to the object you are in, but when you assign an event handler such as onclick, that function is run in the scope of the UI element that was clicked. This means that in your onclick code, this refers to the html object that was clicked, and not the highlightCarouselDot object.
One common solution to this problem is to use an extra variable to store the value of this.
var self = this;
at the start of your object, that way you can refer to self within your event handlers when you want to refer to the outside object.

Categories