How to Hide Element after number of clicks? - javascript

So I need to make an input tag hidden after it has been clicked at least twice. This is the JS/JQuery I have: (note I'm very new to the language)
var clickcounter = 0;
var clicker = document.getElementById("show-img-btn");
$("clicker").click(function(){
clickcounter = clickcounter + 1;
});
if (clickcounter >= 2) {("clicker").style.display = "none;"};
I really don't know the solution to this problem. It could be something as simple as not having enough equal signs or something complex as the whole thing being wrong. Please correct me!

I would use an Immediately Invoked Function Expression (IIFE) to keep the count variable safe from the rest of the scripts on the page.
You need to put all of your logic inside the click event handler, because the rest of the script only runs once.
You can simplify the check by using prefix incrementation of the count variable inside the conditional statement.
(function(count){
$("#show-img-btn").click(function(){
if(++count === 2) this.style.display = 'none';
return false; // returning false prevents form submission
});
})(0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="show-img-btn" value="click me!">
You can simplify it even more if there is nothing else that needs to be done on the second click like so.
(function(count){
$("#show-img-btn").click(function(){
return ++count === 2 && (this.style.display = 'none'), false;
// increment & check; hide on second click; always return false
});
})(0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="show-img-btn" value="click me!">

if (clickcounter >= 2) {("clicker").style.display = "none;"};
if (clickcounter >= 2) {alert("Hello! I am an alert box!!");};
Move this piece of code into the event handler. Otherwise, this is only ran once when your code is parsed, where clickcounter = 0;.
If you put it in $("clicker").click(function(){, it is run every time your event is triggered.

This should help you out,
<div id="clickMe">Click me!</div>
var counter = 0;
var clickMe = document.getElementById("clickMe");
clickMe.addEventListener("click", function () {
counter += 1;
if (counter == 5)
clickMe.style.display = "none";
console.log(counter);
});
You should adapt it to fit you. As you can see I checked the counter each time the div was clicked unlike yours which was once only.
Example
http://jsfiddle.net/xcgh99ut/
Edit 1
Also your code has an error in it.
$("clicker").click(function(){
}
According to your code clicker is variable so it should be,
$(clicker).click(function() {
}
Or using jQuery,
$("#show-img-btn").click(function () {
}

here is a working code: https://jsfiddle.net/xj1noced/
You have to put your condition into the onclick event - so it's run everytime the user clicked the element.
html:
<div id="clicker">
<div id="show-img-btn">Foo</div>
</div>
javascript:
var clickcounter = 0;
var clicker = document.getElementById("show-img-btn");
$("#clicker").click(function(){
clickcounter = clickcounter + 1;
if (clickcounter >= 2) {$("#clicker").css("display", "none")};
});

Related

How do i make a like button that increase counter on first click and decrease on second click

I'm trying to make a like button that counts and decreases just like the typical social media like button
I came up with this js but it just keeps decreasing when clicked.
and I would really appreciate it if I could get help on how to store the counts on my website
function liked(heart){
heart.classList.toggle("liked");
if (heart.liked) {
click ++;
} else {
click --;
}
document.getElementById('clicks').innerHTML = click;
}
Since you didn't give us all your revelant code I'm going to assume some things but you can still use it to help you mimic a like/dislike behaviour
In this example I have 2 buttons a like and a dislike button and both of them call the same function.
<h1 id="counter">10</h1>
<button id="like" onclick="liked(event)">like</button>
<button id="dislike" onclick="liked(event)">dislike</button>
Usually when you click like the common behaviour is counter +1 but the user can also unlike the post or the video, whatever by pressing the button again. Same goes for the dislike button which has a counter-1 behaviour but you can also press it again to return the counter back to what it was before.
You can only have 3 options tho:
Like it = counter+1
dislike it = counter-1
neither of them = counter unchanged
With this code, if like button was pressed and you switch to dislike then the counter will decrease by 2 since it removes the like state you gave it or it can be the other way around and go up by 2 if you go from dislike to like
let like_flag = false;
let dislike_flag = false;
function liked(event) {
let counter = parseFloat(document.getElementById('counter').innerHTML);
var button = event.target.innerText;
switch(button){
case 'like':
if (like_flag==false && dislike_flag==false) {
counter++;
like_flag=true;
} else if (like_flag==false && dislike_flag==true) {
counter = counter + 1; //changed this to 1 instead of 2
like_flag=true;
dislike_flag=false;
} else {
counter--;
like_flag=false;
}
break;
case 'dislike':
if (dislike_flag==false && like_flag==false) {
counter--;
dislike_flag=true;
} else if (dislike_flag==false && like_flag==true) {
counter = counter - 1; //changed this to 1 instead of 2
dislike_flag=true;
like_flag=false;
} else {
counter++;
dislike_flag=false;
}
break;
}
console.log('the button '+button+' was pressed');
document.getElementById('counter').innerHTML = counter;
}
Since both buttons call same function then we use flags and change them from false to true or from true to false. That way we know what button was pressed and what our code should do next. Hope this helps
https://jsfiddle.net/kenpy/p8oesf61/53/
classList.toggle() return a boolean value
so, simply do:
function liked(heart)
{
if (heart.classList.toggle('liked') ) click++;
else click--;
document.getElementById('clicks').textContent = click;
}

How to code a button that only works when clicked multiple times

I am trying to code a simple quiz app. I am trying to put a hidden screen at the end when one clicks on a button 3 times at the end. This is what I have tried:
for (var i = 0; i > 2; i++) {
onEvent("button26", "click", function() {
setScreen("TrollScreen");
playSound("sound://default.mp3", false);
});
}
I am fairly new to code, and I'm not sure how to do this. Help is appreciated.
You need to keep the count of the clicks outside of the event handler. Then inside it you can check that value and show the screen or increase the counter accordingly.
var count = 0;
onEvent("button26", "click", function(){
if(count > 2){
setScreen("TrollScreen");
playSound("sound://default.mp3", false);
}else{
count++;
}
});
Since all DOM elements are actually objects, you can attach a property to them that will serve as a counter, thus when a button gets clicked, you increment that property by 1 and then check if it reached 3 already.
A more subtle approach is to use a helper function that attaches the event and set up the counter as a closured variable, here is how:
function attachEventWithCounter(elem, func, maxClickCount) {
let count = 0;
elem.addEventListener("click", function(e) {
count++;
if(count >= maxClickCount) {
func.call(this, e);
// and probably reset 'count' to 0
}
});
}
You can then use it like so:
attachEventWithCounter(myButton, myEventListener, 3);
attachEventWithCounter just takes a DOM element, a function that will serve as the event listener and a number that will be the maximum amount of tries. It then attaches a click event listener (you could pass in the type of the event as well if you want) and then whenever that event happens, it increments a locally declared variable count (initially set to 0) and checks if it reached the maximum amount of tries, if so it just calls the function passed as parameter (using Function#call to pass a custom this and the event argument to mimic the actual event listener).
Example:
function attachEventWithCounter(elem, func, maxClickCount) {
let count = 0;
elem.addEventListener("click", function(e) {
count++;
if(count >= maxClickCount) {
func.call(this, e);
count = 0;
}
});
}
let btn = document.getElementById("myButton");
function listener() {
alert("Clicked at last!!!");
}
attachEventWithCounter(btn, listener, 3);
<button id="myButton">Click me 3 times</button>
this will click the button three times every time you press it (at least I think). instead, make a counter variable that starts at 0 and increment it up by 1 each time the button is pressed. the put the action you want to perform inside in an if statement ie
if(counter >= 3){
//do some action
}
hope that helps!
you want to keep a counter variable outside the scope of the event to keep track of how many times it was clicked. Ex.
let counter = 0;
onEvent("button26", "click", function() {
if(counter >= 3) {
setScreen("TrollScreen");
playSound("sound://default.mp3", false);
}
counter ++;
});
//create a variable to check how many times the button has been clicked
var buttonClick = 0;
function CheckCount() {
//Check if the buttonClick variable is three
if (buttonClick == 3) {
//if it is equal to three, display the screen and play the sound
//below commented out for sake of demo
//setScreen("TrollScreen");
//playSound("sound://default.mp3", false);
document.getElementById('buttonclickcount').innerHTML = "You clicked it three times";
} else {
//if it is not so, then increment the buttonClick variable by 1
buttonClick++
//so you can see how many times the button has been clicked
document.getElementById('buttonclickcount').innerHTML = buttonClick;
}
};
<!--I would create an onclick event on the button itself that runs a function when -->
<button onclick="CheckCount()">You Win!</button>
<div id="buttonclickcount"></div>
You should look at using closures. This is where you define a variable before returning a function; your returned function closes around this variable. You could do something like in this fiddle.
const button = document.getElementById('button');
const output = document.getElementById('output');
const click = (function() {
let count = 0;
return function() {
count++;
if(count > 3) {
output.innerHTML = 'Count is greater than 3: ' + count
}
}
})();
button.addEventListener('click', click);

Is there a way of binding all double click events to their single click equivalent in jQuery / JavaScript?

I have some jQuery with a lot of different click events. Some of my users are habitual double clickers, which because I have no double click events bound, fires the single click event twice; this can be a pain - for example if one click opens something, and another closes it, double clicking is a zero-sum game.
Is there any way to bind all double click events to their single click equivalent without have the code them individually?
I don't think mapping dblclick to click would help; I'd think it would make things worse, if anything.
You've said you hook up your events using delegation. You could give yourself a function that debounces calls to your event handler:
// Very simple debounce, accepts first event and disregards
// subsequent ones for a period of time
function debouncedHandler(handler, delay) {
delay = delay || 300; // milliseconds, I'm told Windows uses 500 but that seems awfully long
var last;
return function() {
var now = Date.now();
if (last && last + delay > now) {
return false;
}
last = now;
return handler.apply(this, arguments);
};
}
$(document).on("click", "input[type=button]", debouncedHandler(function() {
$(".container").toggleClass("toggle-open toggle-closed");
}));
.toggle-open .closed {
display: none;
}
.toggle-closed .open {
display: none;
}
<input type="button" value="Open/Close">
<div class="container toggle-open">
<span class="open">OPEN</span>
<span class="closed">closed</span>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
HTML
<button class="btn">
click me
</button>
JQUERY
$(document).ready(function(){
var clickDisabled = false;
$('.btn').click(function(){
if (clickDisabled)
return;
// do your real click processing here
console.log('hi');
clickDisabled = true;
setTimeout(function(){clickDisabled = false;}, 5000);
});
});
kindly check https://jsfiddle.net/05tvvaeq/
preventing click handler for 5secs (you can set the time as per your need)
check console to see the result
This is what I would do it:
<input type="hidden" id='counter' value='0'>
<input type="button" value="Save" onclick="save()">
function save(){
var counter = parseInt(document.getElementById("counter").value);
counter = counter+1;
if(counter == 1){
console.log('Saving...')
}
document.getElementById("counter").value = counter;
//after 3 seconds set counter back to 0
setTimeout(function(){
document.getElementById("counter").value = 0;
}, 3000)
}

Modifying HTML elements using jquery

I am trying to use jquery to add and remove a class from <li> elements according to a variable's value ( i ).
Here is a jsfiddle of what I have done so far http://jsfiddle.net/LX8yM/
Clicking the "+" increments i by 1 ( I have checked this with chrome's javascript console ).
One should be able to click "+" and the class .active should be removed from and added to the <li> elements accordingly.
...I can get the first <li> element to accept the class, that's all...
No need for if statements:
$(document).ready(function (){
$('#add').click(function (){
$('.numbers .active').removeClass('active').next().addClass('active');
});
});
jsfiddle
Do note that I added an 'active' class to first list item. You could always do this via JS if you do not have control over the markup.
Your if..else.. is hanging in document.ready. Wrap the increment inside a function and call it respectively.
Like
$(document).ready(function (){
//variable
var i = 1;
//if statments
function incre(i){ // wrap into a function and process it
if(i == 1){
$('#one').addClass('active');
$('#two').removeClass('active');
$('#three').removeClass('active');
}else if(i == 2){
$('#one').removeClass('active');
$('#two').addClass('active');
$('#three').removeClass('active');
}else if(i == 3){
$('#one').removeClass('active');
$('#two').removeClass('active');
$('#three').addClass('active');
}
}
//change i
$('#add').click(function (){
incre(i++); // pass it as a parameter
});
});
Working JSFiddle
This would be easier:
$(document).ready(function(){
var i = 0; // set the first value
$('#something').click(function(){
i++; // every click this gets one higher.
// First remove class, wherever it is:
$('.classname').removeClass('classname');
// Now add where you need it
if( i==1){
$('#one').addClass('classname');
} else if( i==2){
$('#two').addClass('classname');
} else if( i==3){
$('#three').addClass('classname');
}
}):
});
See this code. Initially you have to add class to one.
$(document).ready(function (){
//variable
var i = 1;
$('#one').addClass('active');
//if statments
//change i
$('#add').click(function (){
i++;
if(i == 1){
$('#one').addClass('active');
$('#two').removeClass('active');
$('#three').removeClass('active');
}else if(i == 2){
$('#one').removeClass('active');
$('#two').addClass('active');
$('#three').removeClass('active');
}else if(i == 3){
$('#one').removeClass('active');
$('#two').removeClass('active');
$('#three').addClass('active');
}
});
});
It's being called only once, not in the click event function. This edit of your fiddle works: http://jsfiddle.net/LX8yM/2/
put it in the
'$('#add').click(function (){}'

function in javascript not working when called

I have a javascript code that works by removing the first and the last line of it.
Please take a look at JSFiddle
for people who wants to see it in here, here is my html:
<input id="search" onclick="search()" type="button" value="Search"/>
my javascript :
function search() {
var search = document.getElementById('search');
var int = setInterval(function() {
if (search.value.length == 6)
search.value = 'Searchi';
else if (search.value.length == 7)
search.value = 'Searchin';
else if (search.value.length == 8)
search.value = 'Searching';
else {
search.value= 'Search';
}
//clearInterval( int ); // at some point, clear the setInterval
}, 500);
}
I want the function to work only when I click the button.
You've selected jQuery in jsfiddle.net which by default causes the site to wrap your whole code in a document.ready handler.
The result is that your search function becomes a local function within that wrapper, and not a global variable as required by a DOM0 onclick handler.
Set the jsfiddle options to "no wrap (body)" and "No-Library (pure js)" to turn off that functionality.

Categories