How to add js var inside jquery - javascript

Somehow I can't make the var "turn" change.
--------------'#a3' is a div-----------------
For all of the code go here.
Here is some of the js/jquery:
var turn = 1;
if (turn === 1) {
//----------------------------red
if (da3 === false) {
$('#a3').click(function () {
$(this).css("background-color", "red");
turn = 0;
});
}
if (turn === 0) {
//----------------------------blue
if (da3 === false) {
$('#a3').click(function () {
$(this).css("background-color", "blue");
turn = 1;
});
}
Here is some css I used:
div {
display: inline-block;
background-color:grey;
width : 150px;
height: 150px;
}

It is because you only add one event handler that only does one thing. It is not magically going to add the other one.
Do the if/else logic inside of the click events.

If you want to toggle the background-color by clicking the a3-element, you need to do the if/else checking inside of the event-handler:
bg_state = 0;
$('#a3').click(function () {
if (bg_state===0) {
$(this).css("background-color", "blue");
bg_state=1;
} else {
$(this).css("background-color", "red");
bg_state=0;
}
});
http://jsfiddle.net/ADUV9/
The setting of the event-handler is only executed one time, when the page loads!

Your current code is structured like this:
var turn = 1; // red turn first
if (turn === 1) {
// assign click handlers for red moves
}
if (turn === 0) {
// assign click handlers for blue moves
}
The problem with this is that the only click handlers that will ever be used here are the ones defined in the if (turn === 1) block. The code will not be re-evaluated when you modify turn so the click handlers for blue will never be used.
Instead it should look something like this:
var turn = 1; // red turn first
// example click handler:
$('#a3').click(function () {
// check whose turn it is *inside* of the click handler
if (turn === 0) {
$(this).css("background-color", "blue");
turn = 1;
} else {
$(this).css("background-color", "red");
turn = 0;
}
});
// other click handlers like the above (or better yet, reuse the same function)

Related

Why can I only change the css style once in javascript?

I want to be able to change the backgroundColor of a box between multiple colors using js but I cannot seem to find a way. Is it possible?
window.onload = function() {
var example=document.getElementById("example");
var click=0;
example.addEventListener("click", func);
function func(){
if (click===0){
example.style.backgroundColor=("red");
click=1;
}
if (click===1){
example.style.backgroundColor=("blue");}
click=0;
}
}
Your code checks to see if the value is zero. When it is, it sets it to one. Right after that if statement you see if it is one and set it back to zero.
You need to use else if or just else so it does not evaluate the next if statement.
function func(){
if (click === 0){
example.style.backgroundColor = "red";
click = 1;
}
//else if (click === 1) {
else {
example.style.backgroundColor = "blue";
click = 0;
}
}
Personally I would just toggle a class
var elem = document.querySelector("#test")
elem.addEventListener("click", function () {
elem.classList.toggle("on");
});
div.example {
background-color: blue;
}
div.example.on {
background-color: lime;
}
<div id="test" class="example">Click Me</div>

Function starts being repeated over and over again

I've been developing a simple system that is supposed to change between two different scenes when you press a button.
gameOne();
var game = 1;
function gameOne() {
game = 1;
console.log("Game 1");
$( "body" ).keyup(function( event ) {
if ( event.which == 49 && game == 1) { // Number 1 key
gameTwo();
}
});
}
function gameTwo() {
game = 2;
console.log("Game 2");
$( "body" ).keyup(function( event ) {
if ( event.which == 49 && game == 2) { // Number 1 key
gameOne();
}
});
}
Expected behaviour - I want it to say Game 1, after after pressing the 1 key and then Game 2 after pressing the 1 key again, and then repeat this as I press 1.
Actual behaviour - It does the expected behaviour a few times, and then it starts repeating 1 and 2 over and over again, to the point it lags the browser out.
JSFiddle: https://jsfiddle.net/a0npotm8/10/
I'm really sorry if this is a basic question or anything, I'm still fairly new to Javascript and JQuery and this is really confusing me currently.
All help is appreciated.
Thank you :)
The problem here is that you are rebinding the keyup event recuresively inside the keyup callback, so it ends up by breaking the browser.
What you need to do is to get the keyup binding code out of the two functions:
gameOne();
var game = 1;
$("body").keyup(function(event) {
if (event.which == 49 && game == 1) { // Number 1 key
gameTwo();
} else if (event.which == 49 && game == 2) { // Number 1 key
gameOne();
}
});
function gameOne() {
game = 1;
console.log("Game 1");
}
function gameTwo() {
game = 2;
console.log("Game 2");
}
what about something like:
let game = 1;
document.onkeyup = ev => {
if (ev.which === 49) {
console.log(`Game ${game}`);
game = game === 1 ? 2 : 1;
}
};
will it solve your issue?
You can use a delegate event handler to control actions like this, so you do not have to juggle event bindings around.
var $container = $('#container').focus();
$(document.body)
.on('keyup', '#container.game1', function(e){
if (e.which == 49) {
console.log('Game 1');
$container.removeClass('game1').addClass('game2');
}
})
.on('keyup', '#container.game2', function(e){
if (e.which == 49) {
console.log('Game 2');
$container.removeClass('game2').addClass('game1');
}
});
#container {
min-width: 100vw;
min-height: 100vh;
background-color: rgb(128, 128, 128);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" class="game1" tabindex="0">
</div>
This logic creates two different delegate event handlers for the body. Both filter out events for the #container child element of the body, but also filter based on an additional class on the container; game1 and game2. Depending on which class the element has, only one of the event handlers will process.
Whenever you call keyup on an element, you attach another event handler. To catch events, you only need to call it once. The callback functions that handle the event will fire every time the event happens.

trying to prevent mouseout after link is clicked

I have a navigation with mouseover and mouseout animations. They work. I also have a statement for the click listener that adds a CSS class. The class sets the height of a div, the issue is that the mouseout also alters this div. So I'm trying to figure out a way to disable the mouseout listener when the link is clicked.
I tried to unbind it with no luck
js
var currentDiv;
function slideMenu(e) {
if(e.type === "mouseover"){
// console.log("mouseover");
TweenMax.to($(this).find('div') , 0.25, {height:20});
}
else if(e.type === "mouseout"){
// console.log("mouseout");
TweenMax.to($(this).find('div') , 0.25, {height:1});
}
else if(e.type === "click"){
console.log("click");
if (currentDiv !== undefined){
$(currentDiv).removeClass("selected");
}
currentDiv = $(this).find('div');
$(currentDiv).addClass("selected");
$(currentDiv).unbind('mouseout'); // not working
}
}
$(".menu a").click(slideMenu);
$(".menu a").mouseover(slideMenu);
$(".menu a").mouseout(slideMenu);
css
.selected{
height: 20px;
}
Would this accomplish your goal? Instead of worrying about the binding of click events, you could just check the "selected" class before you do anything else within that click event. Like the following...
var currentDiv;
function slideMenu(e) {
if(e.type === "mouseover"){
// console.log("mouseover");
var child_div = $(this).find("div")
if (!$(child_div).hasClass("selected")) {
TweenMax.to($(this).find('div') , 0.25, {height:20});
} else {
$(child_div).attr("style", "") // remove inline styles attr, so that height is based on css instead of JS
}
}
else if(e.type === "mouseout"){
// console.log("mouseout");
var child_div = $(this).find("div")
if (!$(child_div).hasClass("selected")) { // check to see if selected/clicked on
TweenMax.to($(this).find('div') , 0.25, {height:1})
} else {
$(child_div).attr("style", "") // remove inline styles attr, so that height is based on css instead of JS
}
}
else if(e.type === "click"){
console.log("click", this);
if (currentDiv !== undefined){
$(currentDiv).removeClass("selected");
}
currentDiv = $(this).find('div');
$(currentDiv).addClass("selected");
}
}
$(".menu a").click(slideMenu);
$(".menu a").mouseover(slideMenu);
$(".menu a").mouseout(slideMenu);
If I'm understanding you correctly, you want the height of the element to remain the same size when you click on it and move the mouse off the element. You can try using
var currentDiv;
// add a state
var hasBeenClicked = false;
function slideMenu(e) {
if(e.type === "mouseover"){
TweenMax.to($(this).find('div') , 0.25, {height:20});
}
else if(e.type === "mouseout"){
// only resize if the element hasn't been clicked
if (!hasBeenClicked) {
TweenMax.to($(this).find('div') , 0.25, {height:1});
}
}
else if(e.type === "click"){
// assuming all this stuff is what you want and wasn't testing code
if (currentDiv !== undefined){
$(currentDiv).removeClass("selected");
}
currentDiv = $(this).find('div');
$(currentDiv).addClass("selected");
// set state to true
hasBeenClicked = true;
}
}
Note that this will only work for one element, if you plan to use this function for multiple elements you'll need to have a var hasBeenClicked set up for every element.

Javascript to trigger one function only if two events are both true

Say I want to activate myFunction only if the user has pressed the paragraph with a key and clicks on it. In the case below, the function will get triggered if any of the events is true.
<p id="p1" onClick="myFunction()" onKeyDown="myFunction()">
Text awaiting to be colored in red</p>
<script>
function myFunction(){
document.getElementById("p1").style.color = "red";
}
</script>
You need one extra variable isKeyDown, and isKeyDown should be set to true on keydown, and set to false on keyup.
And than in click callback check is isKeyDown true, call myFunction.
An example of how you could do it. This works with Enter and normally clicking it. Really you don't need to make p focus but I thought it was neat, even though you can still handle the key events from the document and since the click only registers on p there's nothing to worry about.
var p = document.getElementById('p1');
p.addEventListener('mousedown', function(e) {
p.clicked = true;
checkEvents(p);
});
p.addEventListener('mouseup', function(e) {
p.clicked = false;
});
p.addEventListener('keydown', function(e) {
if (e.keyCode === 13) {
p.enterDown = true;
}
});
p.addEventListener('keyup', function(e) {
checkEvents(p);
if (e.keyCode === 13) {
p.enterDown = false;
}
});
function checkEvents(el){
if(el.enterDown && el.clicked){
el.style.backgroundColor = 'red';
}
}
p:focus {
outline: none;
}
<p id="p1" tabindex='0'>
Text awaiting to be colored in red</p>
You'll need to breakdown into two methods. First is keystrokes->click and then click->keystrokes. I'm not sure if this is achievable on pure/vanilla javascaript. But on jquery it goes something like:
$('#p1' ).keydown(function() {
if($('#p1').click()) {
document.getElementById("p1").style.color = "red";
}
});
$('#p1')click(function () {
if($('#p1').keydown()) {
document.getElementById("p1").style.color = "red";
}
});

jQuery mouseenter functions - changing colour if colour isn't already

So, I am not that fluent with jQuery and I have written a bit of code in it that doesn't look as if it works. Here is my code;
$(document).ready(function() {
$("#loginSelector").mouseenter(function() {
if $("#loginSelector").style.backgroundColor != "#3064CA" {
$("#loginSelector").style.backgroundColor = "#3064CA";
};
});
$("#loginSelector").mouseleave(function() {
if $("#loginSelector").style.backgroundColor != "#5990DE" {
$("#loginSelector").style.backgroundColor = "#5990DE";
};
});
$("#signupSelector").mouseenter(function() {
if $("#signupSelector").style.backgroundColor != "#3064CA" {
$("#signupSelector").style.backgroundColor = "#3064CA";
};
});
$("#signupSelector").mouseleave(function() {
if $("#signupSelector").style.backgroundColor != "#5990DE" {
$("#signupSelector").style.backgroundColor = "#5990DE";
};
});
});
All I want the code to do is check to see if the button is not a certain colour, and if it isn't that colour and it is hovered on, it changes to another colour.
Try this and follow the same for the rest of the blocks.
$("#loginSelector").mouseenter(function() { //when hovered on
var desiredColor = "#3064CA"; //define the desired color
if ( $(this).css('color') === desiredColor) return; //if the element's color = the desired color, don't do anything. stop the execution
$(this).css('color', desiredColor); //else set the desired color
});
Assuming the elements initially have the color #5990DE, I'd simply add the following css:
#loginSelector, #signupSelector{
background: #5990DE;
}
#loginSelector:hover, #signupSelector:hover{
background: #3064CA;
}
Or if otherwise,
css:
.onHover{
background: #3064CA;
}
.onLeave{
background: #5990DE;
}
script:
$(document).on('mouseenter', 'loginSelector , #signupSelector', function(){
$(this).addClass('onHover').removeClass('onLeave');
});
$(document).on('mouseleave', '#loginSelector , #signupSelector', function(){
$(this).addClass('onLeave').removeClass('onHover');
});

Categories