I want the buttons to change their color when they're clicked (a darker shade on mousedown and their original color on mouseup) and it works but only on the second click. Why is that? And how can I fix this?
Button id's are 1 through 10 (button1, button2...)
document.getElementById('main').addEventListener('click', function(e) {
var buttonNum = e.target.id.substring(6);
if (e.target.id.substring(0,6) === "button") {
e.target.addEventListener('mousedown', function() {mouseDown(buttonNum)}, false);
e.target.addEventListener('mouseup', function() {mouseUp(buttonNum)}, false);
// trying another way:
// mouseEventHandler(buttonNum);
result.innerHTML = e.target.innerHTML + " was clicked";
}
}, false);
var mouseupColors = ["#CE3737",
"#48935C",
"#FFD454",
"#26567C",
"#FF6528",
"#92898A",
"#AF9FA5",
"#9EA9AA",
"#989788",
"#7C7372"]
var mousedownColors = ["#B52D2D",
"#397A4A",
"#E5BF4B",
"#183F63",
"#E55B24",
"#777071",
"#96888D",
"#879091",
"#7F7E71",
"#635C5B"]
function mouseDown(buttonNum) {
var buttonId = "button" + buttonNum;
document.getElementById(buttonId).style.backgroundColor = mousedownColors[buttonNum - 1];
}
function mouseUp(buttonNum) {
var buttonId = "button" + buttonNum;
document.getElementById(buttonId).style.backgroundColor = mouseupColors[buttonNum - 1];
}
I've also tried creating a function that handles mousedown and mouseup. It has the same result.
var mouseEventHandler = function(buttonNum) {
var buttonId = "button" + buttonNum;
document.getElementById(buttonId).onmousedown = function() {
this.style.backgroundColor = mousedownColors[buttonNum - 1];
};
document.getElementById(buttonId).onmouseup = function() {
this.style.backgroundColor = mouseupColors[buttonNum - 1];
};
};
Here's the fiddle: https://jsfiddle.net/Lj8kyr7e/
mouseup and mousedown events are registered inside click event handler. So the first time the button is clicked, the two events aren't setup yet.
You need to add those events outside of the click handling function. E.g.
https://jsfiddle.net/Lj8kyr7e/6/
Related
I was implementing some audio files today in my Javascript and it works fine. But
I noticed that with each subsequent click the sound gets louder. I alreadio used the "Audio.volume" method but no luck.
My Code:
var AppController = (function () {
var correctItem, secondItem, thirdItem, selectedItems, selectedItemsShuffled;
var rotateImage = function() {
var i = 0;
var randomNumbers = createThreeRandomNumbers();
var interval = window.setInterval(function () {
i++;
document.getElementById("imageToRotate").src= "img/" + items.images[i].imageLink;
if (i === items.images.length -1) {
i = -1;
}
}, 125);
var clearData = function () {
correctItem = "";
secondItem = "";
thirdItem = "";
selectedItems = "";
selectedItemsShuffled = "";
removeNodeChildren("button-1");
removeNodeChildren("button-2");
removeNodeChildren("button-3");
};
var removeNodeChildren = function (obj) {
var myNode = document.getElementById(obj);
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
};
var resetGame = function () {
clearData();
document.getElementById("buttonWrapper").classList.remove("show");
rotateImage();
}
document.getElementById("imageToRotate").addEventListener("click", function (e) {
// select 3 items
correctItem = getSelectedItemDetails(e);
secondItem = getRandomItem(correctItem);
thirdItem = getSecondRandomItem(correctItem, secondItem);
selectedItems = [correctItem, secondItem, thirdItem];
selectedItemsShuffled = shuffleArray(selectedItems);
// create the numbers 1 to 3 randomly
var order = createThreeRandomNumbers();
// remove the rotating effect
clearInterval(interval);
// set the images to the buttons in a random order.
setItemsToButtons(order, selectedItemsShuffled);
//show the buttons
showButtons();
// Create an event which triggers when a button is clicked.
document.getElementById("buttonWrapper").addEventListener("click", function(e) {
var valueOfButtonPressed = e.srcElement.innerText.toLowerCase();
var clickedButton = e.srcElement.id;
if (valueOfButtonPressed === correctItem) {
document.getElementById(clickedButton).innerHTML = e.srcElement.innerText.toLowerCase() + '<span class="icon"><i class="fa fa-check green" aria-hidden="true"></i></span>';
if (!audio) {
var audio = new Audio("audio/correct.mp3");
}
audio.play();
audio.volume = 0.5;
setTimeout(resetGame, 5000);
} else {
document.getElementById(clickedButton).innerHTML = e.srcElement.innerText.toLowerCase() + '<span class="icon"><i class="fa fa-times red" aria-hidden="true"></i></span>';
if (!audio) {
var audio = new Audio("audio/wrong.mp3");
}
audio.play();
audio.volume = 0.5;
setTimeout(resetGame, 5000);
}
});
});
};
// 1: hide the buttons
hidebuttons();
// 2: Replace the title
replaceTitle("Animals");
// 3: set up image rotation until it's clicked.
rotateImage();
})();
Any help will be much appreciated. Cheers!
I'm fairly certain the reason is that you're making a new Audio object with every single click.
Instead of doing this with every click:
var audio = new Audio("audio/correct.mp3");
do a check to see if audio already exists. if it does, then simply do audio.play(). If it does not, THEN you make a new audio object.
So right now, I can dynamically create elements (2 rows of 12 blocks) and when I click on an individual block, I can change the color it as well.
However, I am having two main problems. When I click on the a block to have its color changed, the color picker will pop up beside it, no issues at all. But all the subsequent blocks that I click on, the color picker still pops up beside that first block that was clicked on.
I don't know why this is happening because I do bind the element that was clicked on to the color picker.
My second issue is a minor one but I am unsure of how to go about resolving it: the color picker sometimes appears behind the boxes.
Here is a link to what I have done so far:
http://codepen.io/anon/pen/bwBRmw
var id_num = 1;
var picker = null;
$(function () {
$(document).on('click', ".repeat", function (e) {
e.preventDefault();
var $self = $(this);
var $parent = $self.parent();
if($self.hasClass("add-bottom")){
$parent.after($parent.clone(true).attr("id", "repeatable" + id_num));
id_num = id_num + 1;
//picker = null;
} else {
$parent.before($parent.clone(true).attr("id", "repeatable" + id_num));
id_num = id_num + 1;
//picker = null;
}
});
});
$(".container").on("click", "a", function(e) {
var self = this;
console.log(this.id)
console.log(this)
if(!picker){
console.log("new picker initialized")
picker = new Picker(this)
}
else{
console.log("gets inside else case")
picker.settings = {
parent: this,
orientation: 'right',
x: 'auto',
y: 'auto',
arrow_size: 20
};
//.parent = this;
}
picker.show();
picker.on_done = function(colour) {
$(self).css('background-color',colour.rgba().toString());
picker.hide()
}
e.stopPropagation();
})
I have a container which contains a primary image and 2-3 thumbnails each. I wanted the user to be able to change the image by clicking on the thumbnail of its parent. Aside from that, I want the containers to be draggable/sortable so that users can be able to compare them easily.
This is why I made these 2 self invoking functions in my javascript file.
This one is to change the primary image into the image of the thumbnail.
$(document).ready(function(){
$('.thumb-img').on('click', function(){
var url = $(this).attr('src');
$(this).closest('.item-container').find('.primary-img').attr('src', url);
});
});
While this one is used to drag and drop the containers to interchange positions.
(function() {
"use strict";
var dragAndDropModule = function(draggableElements){
var elemYoureDragging = null
, dataString = 'text/html'
, elementDragged = null
, draggableElementArray = Array.prototype.slice.call(draggableElements) //Turn NodeList into array
, dragonDrop = {}; //Put all our methods in a lovely object
// Change the dataString type since IE doesn't support setData and getData correctly.
dragonDrop.changeDataStringForIe = (function () {
var userAgent = window.navigator.userAgent,
msie = userAgent.indexOf('MSIE '), //Detect IE
trident = userAgent.indexOf('Trident/'); //Detect IE 11
if (msie > 0 || trident > 0) {
dataString = 'Text';
return true;
} else {
return false;
}
})();
dragonDrop.bindDragAndDropAbilities = function(elem) {
elem.setAttribute('draggable', 'true');
elem.addEventListener('dragstart', dragonDrop.handleDragStartMove, false);
elem.addEventListener('dragenter', dragonDrop.handleDragEnter, false);
elem.addEventListener('dragover', dragonDrop.handleDragOver, false);
elem.addEventListener('dragleave', dragonDrop.handleDragLeave, false);
elem.addEventListener('drop', dragonDrop.handleDrop, false);
elem.addEventListener('dragend', dragonDrop.handleDragEnd, false);
};
dragonDrop.handleDragStartMove = function(e) {
var dragImg = document.createElement("img");
dragImg.src = "http://alexhays.com/i/long%20umbrella%20goerge%20bush.jpeg";
elementDragged = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData(dataString, this.innerHTML);
//e.dataTransfer.setDragImage(dragImg, 20, 50); //idk about a drag image
};
dragonDrop.handleDragEnter = function(e) {
if(elementDragged !== this) {
this.style.border = "2px dashed #3a3a3a";
}
};
dragonDrop.handleDragOver = function(e) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
};
dragonDrop.handleDragLeave = function(e) {
this.style.border = "2px solid transparent";
};
dragonDrop.handleDrop = function(e) {
if(elementDragged !== this) {
var data = e.dataTransfer.getData(dataString);
elementDragged.innerHTML = this.innerHTML;
this.innerHTML = e.dataTransfer.getData(dataString);
}
this.style.border = "2px solid transparent";
e.stopPropagation();
return false;
};
dragonDrop.handleDragEnd = function(e) {
this.style.border = "2px solid transparent";
};
// Actiavte Drag and Dropping on whatever element
draggableElementArray.forEach(dragonDrop.bindDragAndDropAbilities);
};
var allDraggableElements = document.querySelectorAll('.draggable-droppable');
dragAndDropModule(allDraggableElements);
})();
The two functions work but when I drag the container and change its position, the first function doesn't work anymore.
It's probably because you drag it and recreate the element node.
you can use Event to solve the problem.
$(document).ready(function(){
// It delegate thumb-img event to body, so whatever you recreate thumb-img,is all right
$('body').on('click', '.thumb-img', function(){
var url = $(this).attr('src');
$(this).closest('.item-container').find('.primary-img').attr('src', url);
});
});
I'm having trouble with my function. I made a text editor with BBcode.
Its working very well but the cursor always get back to the end of the textarea.
Here is how it works;
var element = document.getElementById('textEdit');
var lastFocus;
$(document.body).on('click','.editBout', function(e) {
e.preventDefault();
e.stopPropagation();
var style = ($(this).attr("data-style"));
// Depending on the button I set the BBcode
switch (style) {
case 'bold':
avS = "[b]";
apS = "[/b]";
break;
}
if (lastFocus) {
setTimeout(function () { lastFocus.focus() }, 10);
var textEdit = document.getElementById('textEdit');
var befSel = textEdit.value.substr(0, textEdit.selectionStart);
var aftSel = textEdit.value.substr(textEdit.selectionEnd, textEdit.length);
var select = textEdit.value.substring(textEdit.selectionStart, textEdit.selectionEnd);
textEdit.value = befSel + avS + select + apS + aftSel;
textEdit = textEdit.value
textEdit = BBcoder(textEdit);
document.getElementById('editorPreview').innerHTML = textEdit;
}
return (false);
});
This last part here triggers the preview event
$(document.body).on('blur', '#textEdit', function() {
lastFocus = this;
});
So i want it to come back to last focus but at a given position computed out of my selection + added bbcode length.
I'm an EaselJS newbie. I'm running version 0.7.1. I have a simple game that generates tiles. I would like to remove those tiles whenever they are clicked on. I know my click handler is called for each click event, but my tiles aren't being removed. What am I doing wrong?
c99.Game = (function() {
function Count99Game(){
this.canvas = document.getElementById('game-canvas');
this.stage = new createjs.Stage(this.canvas);
var totalTiles = 10;
for(var i = totalTiles; i>0; i--){
var tile = new c99.Tile(i);
this.stage.addChild(tile);
tile.x = Math.random()*(this.canvas.width - tile.width);
tile.y = Math.random()*(this.canvas.height - tile.height);
tile.addEventListener("click", function(event){
alert("Clicked");
this.stage.removeChild(event.target);
this.stage.update();
}.bind(this));
}
this.stage.update();
}
return Count99Game;
})();