I'm currently in the process of making a website for my band, and one idea I had was that on a specific page, you would see a picture of each band member, and when you hover over it with your mouse the picture would change and you would hear that band member saying something, then when you click on them, they say something else and you'll be redirected to their page.
This alone isn't a problem, but for one member, I want it to take three clicks before you actually get redirected to his page; I also want him to say something different at each click.
So what I'm basically looking for is a way to create different events on the first, second and third click (preferably using javascript).
I hope you guys can help me out, thanks in advance!
Just use variable to count clicks:
var count = 0
$(".test").click(function() {
count++;
if(count == 1) {
$(".test").text("first");
}else if(count == 2){
$(".test").text("second");
}else if(count == 3){
$(".test").text("third");
count = 0;
}
})
http://jsfiddle.net/x83bf1gq/4/
An option could be to create an onclick handler that keeps saying things until all texts in an array of texts are said. Once all the texts have been said, you can just redirect or whatever action you need to be done. Example:
var johnTexts = [
'hello',
'how are you doing',
'come on'
];
var jamesTexts = [
'ready',
'go'
];
var sayTexts = function (texts) {
var i = 0;
return function () {
if (i < texts.length) {
alert(texts[i++]);
} else {
alert('do your redirect or whatever you need');
}
};
}
document.getElementById('john').onclick = sayTexts(johnTexts);
document.getElementById('james').onclick = sayTexts(jamesTexts);
See demo
Simply set an event listener that makes different actions based on a global counter of clicks.
Check this fragment of code:
//set counter
var counter = 0;
var component = document.getElementByID("ID-of-component");
component.addEventListener('mouseover', function(){
//do something
});
component.addEventListener('click', function() {
switch(++counter) {
case 1: /* do something */ break;
case 2: /* do something */ break;
case 3: /* do something */ break;
}
counter = 0; //reset counter
});
Obviously, you have to write this code for each component of your band.
Related
I've been researching how to fix my issue for the past week but can't. I am creating a "click a card and it adds to score" card game but I am having trouble getting the clicks to stop after x amount of cards have already been clicked. I have created a clickCounter function that tracks the clicks and executes with every click. I have also added an isGameOver boolean to stop the function once it hits a certain amount of clicks. However, the boolean doesn't execute as I'd hoped in the clickCounter function.
Long story short: I just want the game to end once x amount of cards have been clicked.
Here is the JavaScript:
let isGameOver = false;
let counter = 0;
const clickCounter = function () {
switch (counter) {
case 0:
case 1:
counter += 1
break;
case 2:
isGameOver; //this is where I want the game to end//
break;
}
//this keeps track of the counts in console//
console.log(`counter equals: ${counter}`);
}
//this is my function that runs everything//
const cardSelection = function () {
randomNumber() //just a function to generate random #//
//beginning of if statement//
if(!isGameOver) {
//CARD ONE//
document.querySelector('#cardOne').addEventListener('click', function (e) {
cardOneFront(); //this changes card appearance, ignore please//
clickCounter(); //clickCounter is being called here//
if (randomNums[0]) {
scoreDisplay.innerText = `SCORE: ${scoreCount += randomNums[0]}`;
console.log(`score just added: ${randomNums[0]}`);
}
this.style.pointerEvents = 'none'
});
//CARD TWO//
document.querySelector('#cardTwo').addEventListener('click', function () {
cardTwoFront(); //this changes card appearance, ignore please//
cardCounter(); //clickCounter is being called here//
if (randomNums[1]) {
scoreDisplay.innerText = `SCORE: ${scoreCount += randomNums[1]}`;
console.log(`score just added: ${randomNums[1]}`);
}
this.style.pointerEvents = 'none'
});
} //if statement ends here//
} //cardSelection function ends here//
cardSelection()
I have visualization of it too. See Here:
what appears in console
I have 10+ cards but I only included two here to keep the code from being super long but the cards all have the similar code and their own individual click events. So, according to the image above, I want card three to not be clickable after counter = 2. But, as you see in the image, even though counter has equaled 2, card 3 is clickable anyways.
I hope this explanation was thorough and I appreciate any help as I am newer to coding. Also, I am coding all of this using vanilla JavaScript.
Thank you!
i think you need to add 'true' to case 2
break;
case 2:
isGameOver = true; //this is where I want the game to end//
break;
}
I guess you already have tried, but i dont see what else would be wrong with the code,
you can also try to add an 'else' to the code. i can only see and If(!isGameOver)
Do the check inside click handlers.
Add card class on each card (this will help to find all cards in one go, so that we can disable each at one place/function).
break;
case 2:
isGameOver = true; //this is where I want the game to end//
disableCards();
break;
}
function disableCards() {
// before doing this add `card` class on each card
let cardsEl = document.querySelector('.card'); // document.getElementsByClassName('card')
for(let i = 0; i< cardsEl.length; i++) {
cardsEl[i].classList.add('disableCard');
}
}
Add CSS into stylesheet
.disableCard {
pointer-events: none;
opacity: 0.7;
}
//CARD ONE//
document.querySelector('#cardOne').addEventListener('click', function (e) {
if(!isGameOver) {
cardOneFront(); //this changes card appearance, ignore please//
clickCounter(); //clickCounter is being called here//
if (randomNums[0]) {
scoreDisplay.innerText = `SCORE: ${scoreCount += randomNums[0]}`;
console.log(`score just added: ${randomNums[0]}`);
}
this.style.pointerEvents = 'none'
}
});
And if click handlers have quite similar code you can register them through for loop. like(it is just suggestion otherwise if the logic is not same for each card you can attach for eachone separatoly)
//add handlers//
for (let I = 0; I< cards.length; i++) {
document.querySelector('#card-'+i).addEventListener('click', function (e) {
if(!isGameOver) {
cardFront(i); //this changes card appearance, ignore please//
clickCounter(); //clickCounter is being called here//
if (randomNums[i]) {
scoreDisplay.innerText = `SCORE: ${scoreCount += randomNums[i]}`;
console.log(`score just added: ${randomNums[i]}`);
}
this.style.pointerEvents = 'none'
}
});
}
You are not setting isGameOver = true
try isgameOver = true in
isGameOver; //this is where I want the game to end// line
I am working client side on a web page that I am unable to edit.
I want to use JS to click on a particular button, but it does not have a unique identifier.
I do know the class and I do know a (unique) string in the innerHTML that I can match with, so I am iterating through the (varying number) of buttons with a while loop looking for the string:
var theResult = '';
var buttonNum = 0;
var searchString = '720p';
while (theResult.indexOf(searchString) == -1
{
theResult = eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum + \"].innerHTML\");
buttonNum++;
}
Now I should know the correct position in the array of buttons (buttonNum-1, I think), but how do I reference this? I have tried:
eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum-1 + \"].click()")
and variation on the position of ()'s in the eval, but I can't get it to work.
You could try something like:
var searchStr = '720p',
// Grab all buttons that have the class 'streambutton'.
buttons = Array.prototype.slice.call(document.querySelectorAll('button.streamButton')),
// Filter all the buttons and select the first one that has the sreachStr in its innerHTML.
buttonToClick = buttons.filter(function( button ) {
return button.innerHTML.indexOf(searchStr) !== -1;
})[0];
You don't need the eval, but you can check all the buttons one by one and just click the button immediately when you find it so you don't have to find it again.
It is not as elegant as what #Shilly suggested, but probably more easily understood if you are new to javascript.
var searchString = '720p';
var buttons = document.getElementsByClassName("streamButton"); // find all streamButtons
if(buttons)
{
// Search all streamButtons until you find the right one
for(var i = 0; i < buttons.length; i++)
{
var button = buttons[i];
var buttonInnerHtml = button.innerHTML;
if (buttonInnerHtml.indexOf(searchString) != -1) {
button.click();
break;
}
}
}
function allOtherClick() {
console.log("Wrong button clicked");
}
function correctButtonClick() {
console.log("Right button clicked");
}
<button class='streamButton' onclick='allOtherClick()'>10</button>
<button class='streamButton' onclick='allOtherClick()'>30</button>
<button class='streamButton' onclick='correctButtonClick()'>720p</button>
<button class='streamButton' onclick='allOtherClick()'>abcd</button>
I would stay clear of eval here, what if the text on the button is some malicious javaScript?
Can you use jQuery? if so, check out contains. You can use it like so:
$(".streamButton:contains('720p')")
I thought that this onClick event in a For loop would help me but when I tried it, it still didn't work.
I am making a simple Battleship game, and while I'm trying to have the user click on only 4 squares to place on ship, the loop keeps going and doesn't stop after 4 tries. I have my onclick even handler in a for loop, but after 4 tries it doesn't stop. I've tried adding a count variable after the end, and even tried adding a break statement but can't get it to work.
Here's my code:
function placeShips() {
var playerTable = document.getElementById("mainPlayer");
var playerCells = playerTable.getElementsByTagName("td");
var count = 1;
alert("Please place the first ship. Click on 4 squares.");
while (count <= 4) {
for (i = 0; i < playerCells.length; i++) {
playerCells[i].onclick = placeBattleship;
}
count++;
}
}
The placeBattleship function contains the code to change the grid square to a background color of red to mark it. My problem is that once the user clicks 4 squares, you can keep going and click on more and more. I can't get the above for loop that calls the placeBattleship function to stop after the user clicks on 4 squares. I've tried putting it in a while loop, and even the solution in the above link, as well as moving the assignment of count, but can't get it to stop after x amount of times (in this case, 4).
Any ideas on what I'm doing wrong, or a better way to do it?
Wouldn't you consider to use jQuery?
Look your function much shorter:
function placeShips() {
$("td:lt(4)").click(placeBattleship);
}
You can testify on the code below:
<table>
<tr>
<td>1.1</td><td>2.1</td>
</tr>
<tr>
<td>1.2</td><td>2.2</td>
</tr>
<tr>
<td>1.3</td><td>2.3</td>
</tr>
</table>
<div id="console"></div>
<script>
$("td:lt(4)").each(function(){
$("#console").append("Content of "+ $(this).html() + "<br/>");
});
$("td:lt(4)").click(function(){
$("#console").append("Clicking "+ $(this).html() + "<br/>");
});
</script>
...or on my Plunker: https://plnkr.co/edit/yNZw6ZhkNfA9E0NdQg7V
So, now we have a solution that stop for 4th click on the squares:
function placeBattleship() {
var $shipDisplay = $("#shipDisplay");
var counter = $shipDisplay.data("counter");
if(counter++ < 4) {
$(this).css("background-color", "red");
$shipDisplay.data("counter", counter);
}
}
function placeShips() {
$("td").click(placeBattleship);
}
$(document).ready(function(){
placeShips();
});
I use a div with id shipDisplay to store a data-attribute for count the clicks.
Look at the plunker: http://plnkr.co/edit/PEba15PSLv2LK6qjY7AD?p=preview
You should separate priorities in your logic and removeEventListener when counter hits 4 , hopefully this helps you :
//defined outside the function
var counter = 0;
playerCells.addEventListener("click" , placeShips );
Then
function placeShips() {
if(counter <= 4){
//Move ship
placeBattleship();
//add to counter
counter++
}else{
//Remove click event if counter reaches 4 .
playerCells.removeEventListener("click" , doSomethingElse)
}
}
You question needs a bit clarification. To my current understanding, you need to move the checking of count to placeBattleship.
What you are doing is binding click to same tds 4 times, not limiting the number of event triggering to 4 times.
// pseudo code
var count = 4; // this is global
var currentCount = 0;
initFunc() {
// bind click events ONCE
}
startPlacing() {
// accept user click and place ship
// set currentCount to zero
}
placeShip() {
// the callback of user `click`
// check for currentCount == count then move on (no more placement)
// increase currentCount by 1
// place ship
}
Note that after an event is triggered, the listener will not be removed. Until you removeEventListener() from it, it will always be listening.
I am having some problems removing parts of a var.
function hotBarClick() {
var likeCount = 0;
$.each(companies, function (key, value) {
if (value.liked) {
likeCount++;
}
if (value.liked && value.alreadyliked ==false) {
var content = value.getHtmlLogo();
matchesHtml.add(content);
this.alreadyliked = true;
}
if (value.liked == false && value.alreadyliked == true) {
var discontent = value.getHtmlLogo();
matchesHtml.remove(discontent);
this.alreadyliked = false;
}
});
I am making a app based on html and javascript. You can like/dislike companies in the neighbourhood. If you liked 5 companies or touch the "hotbar" you will see a slider(owl-carousel) with the logos of the companies you liked.
My problem is that if you liked a company first and then dislike it, i cant remove the images from the slider, that were previously shown.
var matcheshtml is the var containing this infomation. You can see that in my code i add stuff by matcheshtml.add() but i cant seem to use the .remove() method here?
How do i remove the good part?
BTW: i think discontent contains the correct value
I am unrehearsed in javascript and was hoping for some help with a next button that links to an id based on the array. Here is the array
var baseline_next=new Array();
baseline_next[0]="#one";
baseline_next[1]="#two";
baseline_next[2]="#three";
baseline_next[3]="#four";
baseline_next[4]="#five";
baseline_next[5]="#six";
baseline_next[6]="#six2";
baseline_next[7]="#seven";
baseline_next[8]="#eight";
baseline_next[9]="#nine";
baseline_next[10]="#ten";
baseline_next[11]="#eleven";
baseline_next[13]="#thirteen";
baseline_next[14]="#fourteen";
baseline_next[15]="#fifteen";
baseline_next[16]="#sixteen";
baseline_next[17]="#seventeen";
baseline_next[18]="#eighteen";
baseline_next[19]="#nineteen";
baseline_next[20]="#twenty";
baseline_next[21]="#twentyone";
baseline_next[22]="#twentytwo";
baseline_next[22]="#twentythree";
Basically what I need is, when the next button is clicked first ("0" ~ #one) I need the next buttons id to become two, and when clicked again it needs to become #three. I have no idea how to link an array to a button. The reason I need this to happen is because I am using ajax to .load div contents, so the next button doesn't actually submit, it just becomes a new next button. I dont know if it matters, but here is a part of what the button would cause to happen on click.
$('#one').click(function(){
$("#area").hide("slide", { direction: "left" }, 500);
$("#area").load("test_it.jsp #area");
$("#area").show("slide", { direction: "right" }, 500);
$("#two").show();
});
$('#two').click(function(){
if((document.form1.baseline_01[0].checked || document.form1.baseline_01[1].checked| document.form1.baseline_01[2].checked)
&& (document.form1.baseline_02[0].checked || document.form1.baseline_02[1].checked)
&& (document.form1.baseline_03_native.checked || document.form1.baseline_03_asian.checked|| document.form1.baseline_03_black.checked|| document.form1.baseline_03_pacific.checked|| document.form1.baseline_03_white.checked|| document.form1.baseline_03_other.checked)){
if(document.form1.baseline_03_other.checked && document.form1.baseline_03_other_text.value==""){
alert("Please fill in what other race you concider yourself to be.");
return false;
}else{
$("#area").hide("slide", { direction: "left" }, 500);
$("#area").load("test_it.jsp #area2");
$("#area").show("slide", { direction: "right" }, 500);
$("#three").show();
return true;
}
}else{
alert("Please select an answer for each question.");
return false;
}
});
I must apologize in advanced if my question is hard to follow, I just started coding this year.
I think that you should consider reworking your code a bit to not have this list of IDs and use a single class on all of the elements. It would help to see how your HTML is set up to get the next element based on class as well.
Since you already have this array of doom, though, I guess we'll have to use it. Ideally, you have the same class on each element. Let's say, .number.
$(".number").on('click', function () {
var nextID = baseline_next.indexOf(this.id) + 1;
});
If you can't use .number, then you can do the same thing except with a list of every ID that needs to be bound .. ouch. In the above function, nextID should be the index of the ID that comes after the clicked element.
By the way, IDs can be numbers, and you could even use data-id that contains the number. That would be easier too.
OK I really need to ask why are you doing this, are you sure that creating more than 20 ID's called like that is the better way to do want you want?
Anyways, first of all, you can create the array in a shorthand way:
var baseline_next= ["#one", "#two", "#four", "#five", "#six", "#six2" ..., "#twentythree";
(btw "#six2"? really?)
then do something like this:
var counter = 0; // start for the first one
$("#button").on('click', function () {
var id = counter++;
baseline[id]; // and I don't know what you want to do with this, but here it is!
});
Ancient question. (7 years wowzers). Here is some logic that I used for determining the next item in an array using indexOf. This will also start from the beginning once you reach the end of your array.
let options = [true,false,null];
let current = options.indexOf(this.get('order'));
let next = (current+1 > options.length-1 ? 0 : current+1);
this.set('order', options[next]);
It can be simplified as follows:
let baseline_next = ["#one", "#two", "#three"];
Don't use a var as it behaves unpredictably.
Add a variable count to change the index of the array.
let count = 0;
let baseline_next = ["#one", "#two", "#three"];
$(baseline_next[count]).click(function() {
count++;
});
Or
let count = 0;
let baseline_next = ["#one", "#two", "#three"];
$("#one").click(function() {
$(baseline_next[count]).click();
count++;
});