javascript styling two effects at once - javascript

Hello I have a bunch of dynamically created div boxes with IDs div1-div999.
I then grab random boxes and change the animation name to "grow". I want to also change the playstate to "running" but as I have it now just randomly selects another group to change the play states for.
else if (e.keyCode == '40') {
for(var i = 0;i <400; i++){
document.getElementById("div"+Math.floor((Math.random()*1000) + 1 )).style.animationName = "Grow";
document.getElementById("div"+Math.floor((Math.random()*1000) + 1 )).style.animationPlayState = "running";
}
}
I would like to change the animation name and play state of just one group selection. Something like:
document.getElementById("div"+Math.floor((Math.random()*1000) + 1 )).style.animationName = "Grow" / style.animationPlayState = "running";
Is there any way to do this?
Thanks!

How about storing that random group of div ID's inside an array? Hope this helps.
else if (e.keyCode == '40') {
for(var i = 0;i <400; i++){
var randomSelection=[]; //a new array to store all ID's
randomSelection[i]=Math.floor((Math.random()*1000) + 1))
document.getElementById("div"+randomSelection[i].style.animationName = "Grow";
document.getElementById("div"+randomSelection[i].style.animationPlayState = "running";
}
}

Related

Changing background color of only one id instead of all

I've been trying to figure out a way to create a tic tac toe game for school and I'm stuck. I'm trying to change the background color of the div I click on using an if else if. It sort of works but instead of changing the BG color of each individual square I clicked, all 9 squares change colors. If I change the "boxes[i]" to "this", I get an "undefined" and the code only puts an x or an o.
var turns = 'X';
var xColor = "#1772e8";
var oColor = "#e15258";
function changeColor() {
var boxes = document.querySelectorAll(".box");
for (var i = 0; i < boxes.length; i += 1) {
if( turns === 'X' ) {
boxes[i].style.backgroundColor = oColor;
} else {
boxes[i].style.backgroundColor = xColor;
}
}
}
function click() {
if ( this.id === "box1" ) {
if (document.getElementById("box1").innerHTML === ""){
document.getElementById("box1").innerHTML = turns;
changeTurn();
changeColor();
}
}
Any help would be appreciated.
You are selecting every single .box element on the page, which is why they are all changing.
I would try something like this (assuming that you are calling changeColor() from an onClick):
HTML:
<div class="box" onclick="changeColor(this)"> </div>
JS:
function changeColor(clickedBox) {
if( turns === 'X' ) {
clickedBox.style.backgroundColor = oColor;
} else {
clickedBox.style.backgroundColor = xColor;
}
}
By passing the clicked box to the function you know the exact box you have to deal to (note that we pass "this" in the onClick definition, which is why your earlier attempts at using "this" came out as undefined).
EDIT:
Here is an example on Codepen
If jQuery is ok, do this
$(document).ready(function(){
$(".box").click(function(){
//If else statement here
$(this).css("background-color","[color of your choice]");
}
});

tags underneath headings disappear when clicked again w/ javascript no idea why

I have pasted the javascript below but also a link to my codepen so you can see exactly what I am talking about.
I would like the heading to be clicked and expose the text below. On another click I would like for the text to go back to hidden. Multiple headings can be opened at the same time. What is happening with my current setup is you can click once to show, click again to hide and then when you click again to show nothing shows, if you keep clicking the text and headings below are eaten/dissapear. I would prefer to do this without jquery. thanks for any help.
http://codepen.io/jrutishauser/pen/YPrrNa
var clickToShow = function () {
if (this.nextElementSibling.className === 'open'){
this.nextElementSibling.remove('open');
} else if (this.nextElementSibling.className != 'open') {
this.nextElementSibling.className = 'open';
}
};
var articleHeadings = document.getElementsByTagName('h3');
for (var index = 0; index < articleHeadings.length; index++){
articleHeadings[index].onclick = clickToShow;
}
var subArticleHeadings = document.getElementsByTagName('h4');
for (var index2 = 0; index2 < subArticleHeadings.length; index2++){
subArticleHeadings[index2].onclick = clickToShow;
}
Change this.nextElementSibling.remove('open') to this.nextElementSibling.className = ''. I believe remove() method removes the element, not the class.
You can do it like this also. This is the correct way of doing it.
var clickToShow = function () {
element=this.nextElementSibling;
if (element.className === 'open'){
element.className=element.className.replace('open','');
} else if (element.className != 'open') {
element.className = 'open';
}
};

HTML. Hide/Show a drop down menu depending on if an option is selected on another drop down menu

I am trying to have originally just one drop down menu when a website loads. Lets say that drop down menu only has two options "A" and "B". If the user selects option "A" I want another drop menu then to appear on the website (just below the original). If the user selects option "B" I want a different menu to appear below the original. I am also using PHP to make things even more complicated. Can anyone guide me on how I can accomplish this?
Modify the two dropdowns with attribute style="display:none". In your javascript function you would have an event registered that based on the SelectedIndex you would choose which dropdown element to remove the style="display:none" from.
This should do the work :
$("#drop").change(function() {
if( $('#drop option:selected').val() == "A") {
//Do what you want
}
else if ( $('#drop option:selected').val() == "B") {
//Do what you want
}
});
I don't know your level in js, if you need more explanations, please let me know.
Here's an example of manipulating the classes using native JavaScript. It could be cleaner, but it shows how you can check agains what classes exist in order to set CSS behaviour.
var cont = document.body.appendChild(document.createElement('div'));
cont.className = 'row';
for (var i = 0; i < 3; i++ ) {
var menuitem = cont.appendChild(document.createElement('div'));
menuitem.className = 'col';
var internal = menuitem.appendChild(document.createElement('div'));
internal.appendChild(document.createTextNode('item'+ (i + 1)));
(internal.attachEvent) ?
internal.attachEvent('onclick', function () {
for (var j = 0; j < cont.children.length; j++){
if (cont.children[j].className === 'col active') {
cont.children[j].className = 'col';
}
};
this.parentElement.className = 'col active';
}) :
internal.addEventListener('click', function () {
for (var j = 0; j < cont.children.length; j++){
if (cont.children[j].className === 'col active') {
cont.children[j].className = 'col';
}
};
this.parentElement.className = 'col active';
}, false);
};

Flipping 3 text with animation

I have a small requirement. I have a div with three child divs with text. On load the first text will be visible. After 3 seconds the first one hides and second one is visible. After another 3 seconds the second one hides and third one is visible. This continues.
Currently I do not have any animation on the hide of one span and show of another. So it looks kind of murky. White I want is to show some kind of animation as it happens on the windows 8 tiles. Like the text that hides should slide up and disappear and the text that is to be shown should slide in from bottom. the animation should give the user a smooth experience.
I am not using any animation library. Is this possible through javascript / css ? Below is my code. Any idea would be useful.
HTML :
<div class="dataflipping">
<div class="first">FIRST TEXT</div>
<div class="second">SECOND TEXT</div>
<div class="third">THIRD TEXT</div>
</div>
JavaScript:
var srcElement = document.getElementsByClassName("dataflipping");
var elementChld = srcElement.getElementsByTagName("div");
var elementArr = [];
for (counter === 0; counter < elementChld.length; counter++) {
elementArr.push(elementChld[counter]);
}
var elementCount = elementArray.length;
// Set all except first one to hidden initially
for (counter = 1; counter < elementCount; counter++) {
var ele = elementArray[counter];
ele.style.display = "none";
}
counter = 0;
setInterval(function () {
counter++;
var prevElement = null;
var curElement = null;
if (counter === 1) {
var prevElement = elementArr[elementCount - 1];
}
else {
prevElement = elementArr[counter - 2];
}
curElement = elementArr[counter - 1];
prevElement.style.display = "none";
curElement.style.display = "block";
if (counter === elementCount) {
counter = 0;
}
}, 3000);
Girija
IF I understood well. I think easier way is to use MODULO, I wrote something like this:
elementArr[counter%elementCount]
http://jsfiddle.net/t3N4A/
I think you just need to try make position:absolute; and like i change opacity you should change it left/top position, change frequency of setInterval function to make it smoother and make it disappear where u want to. Hope that helped a little.

How to count dynamically created divs

I'm trying to write a form builder where users can generate a signup form. I need to limit the amount of items that the user can create however they also need to delete the items.
Originally I had
var limit = 5;
var counter = 0;
if (counter == limit) {
However when the user deleted items the counter remained the same and so they couldnt replace the deleted form element with a new item. So what I want to do is count how many items are currently active. I tried to do this by giving each new element a class (.kid) and then counting the amount of divs with that class but it didnt work.
Could anyone point me in the right direction? This is what I have so far however it doesn't work.
var limit = 6;
var num = $('.kid').length;
function addAllInputs(divName, inputType){
if (num == limit) {
alert("You have all ready added 6 form items");
}
else {
var newdiv = document.createElement('div');
newdiv.setAttribute('id', 'child' + (counter + 1));
newdiv.setAttribute('class', 'kid' );
Cheers all!
You need to capture the current counter in a closure. Decrease the counter when the user deletes an item and increase it after an item is created. Your code sample doesn't reveal how you handle the deletion, but I'll try to illustrate what I mean with a small code snippet:
$(document).ready(function () {
var limit = 5;
var counter = $('.kid').length;
$('#triggers_delete').click(function () {
/* delete the item */
counter--;
});
$('#triggers_creation').click(function () {
if (counter == limit) {
alert('Limit reached');
return false;
}
/* somehow determine divName and inputType
and create the element */
addAllInputs(divName, inputType);
counter++;
});
});
function addAllInputs(divName, inputType) {
/* just create the item here */
}
Is there any reason an approach like this won't work? Every time you go to add a new DIV, the length of the current collection is examined to see if it meets or exceeds the limit. Of course, you may need to refine the scope of your selector if there could be other DIVs of the form with the same class ID.
var limit = 6;
function addAllInputs(divName, inputType){
if ( $('.kid').length >= limit ) {
alert("You have all ready added 6 form items");
}
else {
var newdiv = document.createElement('div');
newdiv.setAttribute('id', 'child' + (counter + 1));
newdiv.setAttribute('class', 'kid' );
}
Edit: Just a note, I am assuming that you are either removing the deleted items from the DOM or differentiating them from active items with a different class or attribute. Otherwise, the approach I suggested will return a count that includes the deleted items as well.
The only real issue is that your num variable is being defined outside of the function. It will get the number of .kid elements at the time the page loads and will not update. Simply move this line inside the function:
var limit = 6;
function addAllInputs(divName, inputType){
var num = $('.kid').length;
...
Try this
var limit = 6;
function addAllInputs(divName, inputType){
if ($('.kid').length == limit) {
alert("You have all ready added 6 form items");
}
else {
var newdiv = $('div', { 'id': 'child' + (counter + 1), 'class': 'kid' } );
$("inputContainerSelector").append(newdiv);
}

Categories

Resources