javascript: remove/add class function - javascript

i found a very simple javascript function for a slideshow (here).
It works perfectly, but i want to change something about the control buttons. Right now, the play/pause button displays it's own name, like this:
<button class="controls" id="pause">Pause</button>
The javascript is set to run a function called pauseSlideshow under certain circumstances which not only pauses/resumes the slideshow, but also changes the displayed content of the button from "pause" to "play":
var playing = true;
var pauseButton = document.getElementById('pause');
function pauseSlideshow() {
pauseButton.innerHTML = 'Play';
playing = false;
clearInterval(slideInterval);
}
now, what i want to do is to leave the button empty and work width background images, and to do that i planned to do a simple class swap whenever the pauseSlideshow function is triggered. So, first i added a class called pause to the button with the desired background image set in the style:
<button class="controls pause" id="pause"></button>
and next i was going to do something like this:
var playing = true;
var pauseButton = document.getElementById('pause');
function pauseSlideshow() {
pauseButton.removeClass('pause');
pauseButton.addClass('play');
playing = false;
clearInterval(slideInterval);
}
(where play is another class with a different background image). Sufficient to say, as soon as pauseSlideshow runs, the function crashes. I'm writing something wrong or in the wrong place, but i know that the approach is viable.
please, can anybody point out the error?
EDIT:
Use $(pauseButton).removeClass('pause'); and
$(pauseButton).addClass('play');. addClass and removeCalss are jQuery
methods. And you need to add jQuery reference too. – user3698428
document.getElementById("pause") does not return a jQuery element.
.removeClass() and .addClass() are jQuery functions. So basically you
are trying to call jQuery functions on a non-jQuery element and it's
throwing an error. Change it to var pauseButton = $("#pause"); or
$(pauseButton).removeClass(...); $(pauseButton).addClass(...);
when i try either way, console returns: Uncaught ReferenceError: $ is not defined

When working in pure javascript, you should use this to add or remove class:
pauseButton.classList.remove('pause');
pauseButton.classList.add('play');
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

Related

The onclick is not working on first click

I am working on one JavaScript project, where I need to toggle between Celsius and Fahrenheit.
The HTML is here
<button onclick="toggleCF();" id="toggleCF" class="button">Toggle C/F</button>
And here is the JavaScript Function
this.toggleCF = function() {
console.log('click');
var fahrenheit = document.getElementById('toggleFahrenheit');
var celsius = document.getElementById('toggleCelsius');
if (fahrenheit.style.display === 'none') {
fahrenheit.style.display = 'block';
celsius.style.display = 'none';
} else {
fahrenheit.style.display = 'none';
celsius.style.display = 'block';
}
}
The CSS I used is given
.temperature-celsius {
}
.temperature-fahrenheit {
display: none;
}
If you want to check this application live here is the link
Please click on this link to see app in running form
If you visit the above link and check, you will find that on first click the toggle didn't work. But when you click the second time then it starts working normally.
When the app is first loaded, both the toggleFahrenheit and toggleCelsius divs have no style attribute. They are getting display rules from the CSS, true, but they have no style on themselves.
So think about what your code sees, then. fahrenheit.style.display is null because that block doesn't have the style attribute yet. Therefore, fahrenheit.style.display === 'none' evaluates to false. As a result, the else block is executed and you end up displaying Celsius. Unfortunately, this is the default block which is shown, so the first click doesn't do anything.
The second click works because after the code executes once, now both div blocks have a style attribute.
To fix this, you should either put default style attributes onto the div tags or flip the logic in the code so you check on the Celsius block first, since that's the default display.
Personally, I would use classes to toggle display behaviour instead.
function toggle() {
var fahrenheit = document.getElementById("fahrenheit");
var celsius = document.getElementById("celsius");
fahrenheit.classList.toggle('hide');
celsius.classList.toggle('hide');
}
.hide { display: none; }
<div id="fahrenheit" class="hide">-40 F</div>
<div id="celsius">-40 C</div>
<button onclick="toggle()">Toggle</button>
And yes, I use -40 degrees in the example because I'm lazy and I happen to know this is the same temperature in both systems (:
It does not work because this if (fahrenheit.style.display === 'none') will return NULL as there is no inline style on the element. this method won't "look" at CSS, it only works for inline styles. You could try this:
var element = document.getElementById('toggleFahrenheit'),
style = window.getComputedStyle(element),
top = style.getPropertyValue('top');
to check the CSS properties in pure JS or you could use JQuery which would solve it in one line of code.
This often happen most of the time on your css content not being been loaded up fully i have my issue solved with the following code:
function yourFunction() {
document.addEventListener("DOMContentLoaded", function(){
// you works start here
});
}
The simple solution is to use the EventListener .
I had the same problem with the onclick but when using :
const myEl = document.getElementById('myBtn');
myEl.addEventListener('click', function () {
//Your code here
});
It works on first click!

EaselJS: AS3 to Javascript conversion: on rollover of MC, gotoAndPlay frame 1 of that MC (Flash Canvas for HTML5)

This is a Javascript issue, for an HTML5 canvas project in Flash. I'm trying to get movieClip cta to act as a button, and once it's moused over to play this.cta.gotoAndPlay(1);. I'm using the code from the suggested snippets in Flash Canvas and I'm getting the following error on mouseover: TypeError: this.cta is undefined So how do I call cta from inside this function?
FYI, the alert works in the code below (when the MC is moused over), and this.cta.gotoAndPlay(1); works also when placed in the timeline by itself outside of this codeblock.
Here's the javascript flash(canvas) is suggesting in the code snippet.
var frequency = 3;
stage.enableMouseOver(frequency);
this.cta.addEventListener("mouseover", fl_MouseOverHandler);
function fl_MouseOverHandler()
{
alert("Moused over");
this.cta.gotoAndPlay(1);
}
Here's the old AS3.
cta.onRollOver = function(){
this.gotoAndPlay("start");
I figured it out. I added .bind(this) on the end of fl_MouseOverHandler in the EventListener. It works for me.
var frequency = 100;
stage.enableMouseOver(frequency);
this.cta.addEventListener("mouseover", fl_MouseOverHandler.bind(this));
function fl_MouseOverHandler()
{
this.cta.gotoAndPlay(1);
}
your event listener is not setup properly by the looks of it a mouse event should look like:
this.cta.addEventListener(MouseEvent.ROLL_OVER, fl_MouseOverHandler);
unless you are listening to another customEvent then you will need to direct it to where it is listening to for the event.
also just to point out if you are looking at something within the same movieClip as long as it has an instance name in that same movieclip you do not need to put this at the start it can just be:
cta.addEventListener(MouseEvent.ROLL_OVER, fl_MouseOverHandler);

Button.onclick automatically triggers, then will not trigger again

I have a script, which I'm using to try and display only one section of a webpage at a time.
function showMe(id){ clearPage(); changeDisplay(id, "block"); console.log(id)}
Currently, I'm using buttons to change which section is displayed.
var aBtn = document.getElementById("a-btn");
var otherBtn = document.getElementById("other-btn");
aBtn.onclick=showMe("a-btn-section-id");
otherBtn.onclick=showMe("other-btn-section-id");
However, when I load the page, the following happens:
I see the function attached to each button activate once in sequence in the console.
The page refuses to respond to further button inputs.
Testing with the console shows that showMe() and the functions it calls still all work properly. I'm sure I'm making a very basic, beginner mistake (which, hopefully, is why I can't find this problem when I Google/search StackOverflow/read event handling docs), but I'm at a loss for what that mistake is. Why would my script assume my buttons are clicked on load, and why won't it let me click them again?
You're calling the function an assign the value to onclick property instead of attach the function, try defining your onclick property as:
aBtn.onclick=function(){showMe("a-btn-section-id");};
otherBtn.onclick=function(){showMe("other-btn-section-id");};
Try the follow jsfiddle:
function showMe(id){ // some stuff..
console.log(id)
}
var aBtn = document.getElementById("a-btn");
var otherBtn = document.getElementById("other-btn");
aBtn.onclick=function(){showMe("a-btn-section-id");};
otherBtn.onclick=function(){showMe("other-btn-section-id");};
<input type="button" value="a-btn" id="a-btn"/>
<input type="button" value="other-btn" id="other-btn"/>
Hope this helps,

KineticJS circles won't respond to clicks

//Sets up endgame and text variables for later use
var final = '';
var message = '';
var endGame = false;
//Ends the game by disabling input
function endGame(){
feedButton.off('click');
hydrateButton.off('click');
sleepButton.off('click');
entertainButton.off('click');
startButton.off('click');
}
function gameStart(){
healthDrop();
sanityDrop();
patienceDrop();
difficult();
randOne();
randTwo();
randThree();
randFour();
function indicateBegin(){
imgk.setAttrs({fill: 'purple'});
}
function indicateOff(){
imgk.setAttrs({fill: false});
}
var timer = setTimeout(indicateOff, 4000);
}
//Should ready KineticJS buttons for use
startButton.on('click', gameStart);
feedButton.on('click', tamaHibachi.feed);
hydrateButton.on('click', tamaHibachi.hydrate);
sleepButton.on('click', tamaHibachi.sleep);
entertainButton.on('click', tamaHibachi.entertain);
So, I've been trying to create a game in KineticJS for a class project, but I've found that none of my buttons work. I don't know if the problem lies in this part of the code, but I would believe it does. Can anyone help?
Without more info on your code it's hard to say anything. For instance, all my objects have 'ID's... container is a DIV with an id of 'container' so that you can then do this:
container.addEventListener('mousedown', startListening, false );
I can't tell from your code if you have all that set up right. It's probably nothing with Kinetic, because I have a huge project on the go with Kinetic and all the event listeners are working just fine.

Hammer.js Carousel Start Pane

Heyho,
I´am working on a project in my university and I´d like to use "Hammer.js".
I´ve downloaded the Carousel-Example and it works perfectly for me.
But I would like to start a the middle pane of my code and it´s not so simple I think.
It´s something like this:
http://img203.imageshack.us/img203/6326/schemeas.jpg
so Hammer.js starts always with the green screen. But I like to start with the yellow one.
I´ve added one swipe right to the init function but it looks horrible when the page is loading and could not be the goal ^^
I hope anyone of you have an idea how to solve my problem.
Try calling
carousel.showPane(1);
That will display the second pane instantly. You will want to put this near the bottom, right after where it says.
carousel.init();
If you're feeling adventurous you could try and make it automatically start with that pane as there's a variable inside the Carousel function called current_pane which is set to a default of 0 (the first pane). Altering this may work too but might require more code somewhere else. Experiment!
edit
NULL is right, it does animate it. Here's a more in depth method to set it without animation:
I found that the method responsible for changing which pane is showing was the setContainerOffset mthod which could be passed a variable to animate it. I previously told you to use showPane(2) but that then called
setContainerOffset(offset, true)
which caused the animation occur. What you should do instead is make a slightly different version of showPane...
this.setPane = function( index ) {
// between the bounds
index = Math.max(0, Math.min(index, pane_count-1));
current_pane = index;
var offset = -((100/pane_count)*current_pane);
setContainerOffset(offset, false);
};
You'll find it's almost identical to showPane except for the name and the fact that it calls setContainerOffset with animation: false. This will immediately show the pane of your choice and can be called using
carousel.setPane(index);
What I've done is added this to the init function so that it looks like this:
this.init = function() {
setPaneDimensions();
var c = this;
$(window).on("load resize orientationchange", function() {
setPaneDimensions();
c.setPane(current_pane);
//updateOffset();
})
};
Now you can change
var current_pane = 0;
to whatever you want and the carousel will always start with that pane when it's initialised! simple!

Categories