If statement for an autoclicker - javascript

Im trying to make a clicker game, and when the clicks reach a certain number, something happens. Nothing happens. Any ideas as to why the if statement I added isnt doing anything when reaching the number of ten clicks?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Clicker</title>
<script src="counter.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/css/bootstrap.min.css" integrity="2hfp1SzUoho7/TsGGGDaFdsuuDL0LX2hnUp6VkX3CUQ2K4K+xjboZdsXyp4oUHZj" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js" integrity="sha384-THPy051/pYDQGanwU6poAc/hOdQxjnOEXzbT+OuUAFqNqFjL+4IGLBgCJC3ZOShY" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.2.0/js/tether.min.js" integrity="sha384-Plbmg8JY28KFelvJVai01l8WyZzrYWG825m+cZ0eDDS1f7d/js6ikvy1+X+guPIB" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/js/bootstrap.min.js" integrity="VjEeINv9OSwtWFLAtmc4JCtEJXXBub00gtSnszmspDLCtC0I4z4nqz7rEFbIZLLU" crossorigin="anonymous"></script>
<style>
body{
text-align: center;
background-image: url("https://gift-frog.com/wp-content/uploads/2016/06/off-white-textured-background-1920x10803.jpg");
}
h1{
font-size: 100px;
color: #372424;
}
h3{
color: #372424;
}
h2{
color: #372424;
}
*.unselectable {
-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
/*
Introduced in IE 10.
See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
*/
-ms-user-select: none;
user-select: none;
}
</style>
</head>
<body id="body" onclick="doClick()">
<nav class="navbar navbar-dark navbar-inverse">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#exCollapsingNavbar" aria-controls="exCollapsingNavbar" aria-expanded="false" aria-label="Toggle navigation">
☰
</button>
<div class="collapse" id="exCollapsingNavbar">
<div class="bg-inverse p-a-1">
<h4>Your Statistics</h4>
<span class="text-muted">graph in development</span>
<br>
<h4>Rank</h4>
<progress class="progress progress-success" value="bob" max="500"></progress>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-sm-4">
</div>
<div class="col-sm-4">
<h1 class="unselectable">Clicked <h1 class="unselectable" id="counter">0</h1></h1> <h1 class="unselectable">times</h1>
</div>
<div class="col-sm-4">
</div>
</div>
</div>
</body>
</html>
Here is the javascript for it.
/**
* Created by Illuminati on 9/8/2016.
*/
var clicks = 0;
var multiplyer = 0;
function doClick() {
clicks = clicks + 1;
var theCounter = document.getElementById('counter');
theCounter.textContent = clicks;
}
if(clicks == 10){
alert("test");
}

Move the conditional to inside the function. Outside of it, it's only being read on page load where it is always false.

The if block you have only ever runs once, but your event handler runs whenever the user click on the button.
Something like this:
function doClick() {
clicks += 1;
var theCounter = document.getElementById('counter');
theCounter.textContent = clicks;
if(clicks == 10){
alert("test");
}
}
Also instead of doing, counter = counter + 1 you could also use, clicks += 1 which is the exact same thing.

Related

Create a custom/prettier confirm() and use it in if() statement

The closest I found researching for what I was looking for is this: Making a confirm box
Unfortunately, I could not make it do exactly what I wanted or I didn't understand. I am new to Java/Javascript and HTML.
I am using Google Scripts to create a custom user interface for, Google Sheets to make capturing the input needed user friendly. I am stuck on trying to include a custom confirm in my validation code. To test it I just created a simple web app with below code: (I created some Psuedo code and commented it out in the myFunction function within the code below)
function doGet(){
var template = HtmlService.createTemplateFromFile('Basic');
return template.evaluate()
.setTitle('Example App')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
.confirmBox {
display: none;
background-color: rgba(0, 0, 0, 0.40);
border: 1px solid #ddd;
position: fixed;
-webkit-transition: -webkit-box-shadow .25s;
transition: -webkit-box-shadow .25s;
transition: box-shadow .25s;
transition: box-shadow .25s, -webkit-box-shadow .25s;
border-radius: 2px;
width: 250px;
left: 50%;
margin-left: -100px;
padding: 6px 8px 8px;
box-sizing: border-box;
text-align: center;
color: #ffffff;
font-size: 24px;
z-index:99;
}
.confirm .message {
text-align: left;
}
</style>
</head>
<body>
<div id="cfrmBox" class="confirmBox">
<div id="cfrmBoxMsg" class="message"></div>
<button id="idYesButton" class="btn waves-effect waves-light z-depth-5" >Yes</button>
<button id="idNoButton" class="btn waves-effect waves-light z-depth-5" >No</button>
</div>
<div class="container">
<div class="row">
<div class="col s12">
<br><br>
<div class="card">
<div class="card-image">
<span class="card-title">Timer</span>
<a class="btn-floating halfway-fab waves-effect waves-light teal z-depth-5 tooltipped"
data-position="top"
data-tooltip="Press to start and stop timer" onclick="startStopTimer()">
<i id="idStopWatch" class="large material-icons">access_time</i></a>
</div>
<div id ="idCardContent" class="card-content" style="color: #4db6ac;
font-weight: bold;
font-weight: 150%">
<p id = "idCardContentP">04:10:24</p>
</div>
</div>
<button class="btn waves-effect waves-light z-depth-5" id="btnNextTask" onclick="myFunction()">Next Task
<i class="material-icons right">music_note</i>
</button>
</div> <!-- END col END -->
</div> <!-- END row END -->
</div> <!-- END Container -->
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"> </script>
<script>
function appearNow(tMessage){
var x = document.getElementById('cfrmBoxMsg');
x.innerHTML = tMessage;
var y = document.getElementById('cfrmBox');
y.style.display = "inline";
}
function myFunction() {
var stTime = document.getElementById('idCardContentP').innerHTML;
if (stTime != "") {
//Had function left in front. Corrected
appearNow('Do you want to save your time for this task?')
// This is where I want to capture if the 'yes' or 'no' button was pressed
//Psuedo code below
/*
if(document.getElementById('idYesButton').click == true){
y.style.display = "none";
M.toast({html: 'You clicked YES and time has been saved and here is the next task'});
} else {
y.style.display = "none";
M.toast({html: 'You clicked NO and we will do nothing'});
}
*/
//Continue with more validation code
} else {
M.toast({html: 'Since the timer has not started you can freely move to the next task'});
}
}
function startStopTimer() {
M.toast({html: 'Timer is hard coded to be greater than 0 for testing!'});
}
</script>
</body>
</html>
I greatly appreciate any help.
It really seems like nested if statements to create one function to do one particular set of validations isn't really workable in this world since once a function is called it has to complete unless the built-in confirm() is called which is practical but ugly. So I had to rethink my logic route and realized to do what I want and have a custom confirm box I can't make it a nice reusable, neat and tidy function. I have to create a separate function for each validation and create a new '
<div id="cfrmBox" class="confirmBox">
' each time I want to use it, with the buttons that call a specific function with the 'onclick' each time specific to that validation. This can, in my opinion, make the code bulky. But, it works.
function doGet(){
var template = HtmlService.createTemplateFromFile('Basic');
return template.evaluate()
.setTitle('Example App')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
.confirmBox {
display: none;
background-color: rgba(0, 0, 0, 0.40);
border: 1px solid #ddd;
position: fixed;
-webkit-transition: -webkit-box-shadow .25s;
transition: -webkit-box-shadow .25s;
transition: box-shadow .25s;
transition: box-shadow .25s, -webkit-box-shadow .25s;
border-radius: 2px;
width: 250px;
left: 50%;
margin-left: -100px;
padding: 6px 8px 8px;
box-sizing: border-box;
text-align: center;
color: #ffffff;
font-size: 24px;
z-index:99;
}
.confirm .message {
text-align: left;
}
</style>
</head>
<body>
<div id="cfrmBox" class="confirmBox">
<div id="cfrmBoxMsg" class="message"></div>
<button id="idYesButton" class="btn waves-effect waves-light z-depth-5" value="yes" onclick="confirmYesNo(this.value)">Yes</button>
<button id="idNoButton" class="btn waves-effect waves-light z-depth-5" value="no" onclick="confirmYesNo(this.value)">No</button>
</div>
<div id="idContainer" class="container">
<div class="row">
<div class="col s12">
<br><br>
<div class="card">
<div class="card-image">
<span class="card-title">Timer</span>
<a id="idStopWatchBtn" class="btn-floating halfway-fab waves-effect waves-light teal z-depth-5 tooltipped"
data-position="top"
data-tooltip="Press to start and stop timer" onclick="startStopTimer()">
<i id="idStopWatch" class="large material-icons">access_time</i></a>
</div>
<div id ="idCardContent" class="card-content" style="color: #4db6ac;
font-weight: bold;
font-weight: 150%">
<p id = "idCardContentP">04:10:24</p>
</div>
</div>
<div class="row">
<div class="col s12">
<div id="idCardPanel" class="card-panel teal">
<span id="idCardPanelSpan"class="white-text">Task 1: Do something fun
</span>
</div>
</div>
</div>
<button class="btn waves-effect waves-light z-depth-5" id="btnNextTask" onclick="myFunction()">Next Task
<i class="material-icons right">music_note</i>
</button>
</div> <!-- END col END -->
</div> <!-- END row END -->
</div> <!-- END Container -->
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"> </script>
<script>
function appearNow(tMessage){
var x = document.getElementById('cfrmBoxMsg');
x.innerHTML = tMessage;
var y = document.getElementById('cfrmBox');
y.style.display = "inline";
}
function myFunction() {
var stTime = document.getElementById('idCardContentP').innerHTML;
if (stTime != "") {
document.getElementById("idStopWatchBtn").classList.add("disabled");
document.getElementById("btnNextTask").classList.add("disabled");
appearNow('Do you want to save your time for this task?')
} else {
document.getElementById('idCardPanelSpan').innerHTML = "Task 2: Do something even funner!";
M.toast({html: 'Since the timer has not started you can freely move to the next task'});
}
}
function startStopTimer() {
M.toast({html: 'Timer is hard coded to be greater than 0 for testing!'});
}
function confirmYesNo(btnValue){
switch (btnValue) {
case "yes":
document.getElementById('idCardContentP').innerHTML = '';
showHideElements('cfrmBox');
M.toast({html: 'You clicked yes.'});
//Since timer is blank it will hit code to move to next task
myFunction();
break;
case "no":
showHideElements('cfrmBox');
M.toast({html: 'You clicked no so nothing happens'});
break;
default:
M.toast({html: 'Oops this should not happen'});
}
document.getElementById("idStopWatchBtn").classList.remove("disabled");
document.getElementById("btnNextTask").classList.remove("disabled");
}
function showHideElements(showHideWhat) {
//Be careful with this function if you start with display block versus inline
var x = document.getElementById(showHideWhat);
if (x.style.display !== "none") {
x.style.display = "none";
} else {
x.style.display = "inline";
}
}
</script>
</body>
</html>

How can I reset my checkbox to be unchecked when modal box is closed?

I have created a modal box. Within my modal box there is text. The text is named publication and changes color between blue and red. The text changing color is linked to a checkbox being checked and unchecked.
I want the checkbox to be unchecked every time the modal box is opened and re-opened after being closed.
I have tried using $('input[type=checkbox]').prop('checked',false); but the checkbox is not always unchecked after the modal box is closed.
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<!-- Remember to include jQuery :) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<!-- jQuery Modal -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />
</head>
<style>
.onlyThese{
cursor:pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
input[type="checkbox"]+label { color:blue }
input[type="checkbox"] { display: none }
input[type="checkbox"]:checked+label { color:red }
}
input:focus{
outline: none;
}
</style>
<p> <a class="btn" href="#ex5">Sectors </a> </p>
<div id="ex5"; class="modal"; style="background-color:white">
<div style="float:left;">
<p> <input type="checkbox" id="group1" class="yourCheckbox" > <label for="group1" class="onlyThese">Publication </label> </p>
<div id="myDiv">the preparation and issuing of a book, journal, or piece of music for public sale.</div>
</div>
<div>
<p style="float:right">
<b>Apply</b>
</p>
</div>
</div>
<script>
$('a[href="#ex5"]').click(function(event) {
event.preventDefault();
$(this).modal({
escapeClose: false,
clickClose: false,
showClose: false,
});
});
$('.yourCheckbox').change(function(){
if($(this).prop("checked")) {
$('#myDiv').show();
} else {
$('#myDiv').hide();
}
});
$('input[type=checkbox]').prop('checked',false);
</script>
I expect:
-the user to click on the modal box named sectors
the modal box to open and the text publication to be blue which is
when it is unchecked
-the user may choose to click apply which closes the modal box; but they can then open it again but the checkbox is now unchecked and the
user has to then proceed to click on the text to check the checkbox
again.
You could move the $('input[type=checkbox]').prop('checked',false); statement where you're initializing the modal each time:
$('a[href="#ex5"]').click(function(event) {
event.preventDefault();
$(this).modal({
escapeClose: false,
clickClose: false,
showClose: false,
});
$('#myDiv').hide();
$('input[type=checkbox]').prop('checked', false);
});
$('.yourCheckbox').change(function() {
if ($(this).prop("checked")) {
$('#myDiv').show();
} else {
$('#myDiv').hide();
}
});
.onlyThese {
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
input[type="checkbox"]+label {
color: blue
}
input[type="checkbox"] {
display: none
}
input[type="checkbox"]:checked+label {
color: red
}
}
input:focus {
outline: none;
}
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<!-- Remember to include jQuery :) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<!-- jQuery Modal -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />
</head>
<p>
<a class="btn" href="#ex5">Sectors </a>
</p>
<div id="ex5" ; class="modal" ; style="background-color:white">
<div style="float:left;">
<p>
<input type="checkbox" id="group1" class="yourCheckbox" />
<label for="group1" class="onlyThese">Publication </label>
</p>
<div id="myDiv">the preparation and issuing of a book, journal, or piece of music for public sale.</div>
<div>
<p style="float:right">
<b>Apply</b>
</p>
</div>
</div>
</div>

How do I loop through HTML elements while executing a function on each element

I am a newbie to Javascript, I wanted to implement a for loop that would go through each div as selected by its class.
The simple idea is to reveal DIVs when I click on a button. But it has to be sequential: I click DIV1 appears, when I click again DIV2 appears and so on. Currently my code only changes the class of one DIV and not the rest. Here are my code samples:
$(document).ready(function(){
// jQuery methods go here...
var count = document.getElementById("page1").childElementCount;
for(var i = 0; i < count; i++){
var myClass = ".panel" + i;
$("button").click(function(){
$(myClass).addClass("showing animated fadeIn")
});
}
});/**document ready **/
.showing{
background-color: red;
height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<link rel="stylesheet" type="text/css" href="animate.css">
</head>
<body>
<button class="one">Click Me!</button>
<div id="page1">
<div class="panel1">
</div>
<div class="panel2">
</div>
<div class="panel3">
</div>
<div class="panel4">
</div>
</div><!-- page one -->
<div id="trial">
</div>
<script src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="jquery.touchSwipe.min.js"></script>
<script type="text/javascript" src="trial.js"></script>
</body>
</html>
Please let me know what I am missing especially in the for loop or if I can do something else to be able to grab a DIV and add a class every time I click on the button.
Firstly, the HTML attribute class is made for multiple elements with the same style/behaviour. You should use id if it is to dissociate one panel for another.
You have to store a count variable to know which panel has to appear next.
And always try to do what you want in Javascript without jQuery if it is possible !
var i = 1;
function clickBtn() {
if (!document.getElementById("panel-" + i))
return;
document.getElementById("panel-" + i).classList.add("visible");
i++;
}
.panel {
width: 50px;
height: 50px;
display: none;
margin: 5px;
background-color: #bbb;
}
.panel.visible {
display: block;
}
<button onclick="clickBtn()">click me</button>
<div>
<div id="panel-1" class="panel"></div>
<div id="panel-2" class="panel"></div>
<div id="panel-3" class="panel"></div>
<div id="panel-4" class="panel"></div>
</div>
You could use counter like clickCount instead of for loop
$(document).ready(function(){
// jQuery methods go here...
var clickCount = 1;
$("button").click(function(){
var myClass = ".panel" + clickCount;
$(myClass).addClass("showing animated fadeIn")
clickCount++;
});
});/**document ready **/
.showing{
background-color: red;
height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<link rel="stylesheet" type="text/css" href="animate.css">
</head>
<body>
<button class="one">Click Me!</button>
<div id="page1">
<div class="panel1">
</div>
<div class="panel2">
</div>
<div class="panel3">
</div>
<div class="panel4">
</div>
</div><!-- page one -->
<div id="trial">
</div>
<script src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="jquery.touchSwipe.min.js"></script>
<script type="text/javascript" src="trial.js"></script>
</body>
</html>
You've got this a little bit backwards; you're trying to attach an event handler to the button for each element. Instead, you should have one event handler for the button, which cycles through the elements.
You could set a variable to keep track of which element is currently highlit, but it's easier to just determine that based on the current state of the DOM:
$(document).ready(function() {
$('button.one').click(function() {
$('.showing') // find the current element
.removeClass('showing') // clear it
.next() // find its next sibling
.addClass('showing'); // show that
if ($('.showing').length === 0) {
// nothing is showing, so show the first one
$('#page1 div:eq(0)').addClass('showing')
}
})
})
#page1 div {height: 10px}
#page1 div.showing {background-color: red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="one">Click Me!</button>
<div id="page1">
<div class="panel1"></div>
<div class="panel2"></div>
<div class="panel3"></div>
<div class="panel4"> </div>
</div>
There's a small cheat in the above -- if the current element is the last one, then it won't have a next() to highlight. That's why I waited to check for the case where there's nothing visible until after moving the highlight; that way it will work for both the first click, and for when you need the highlight to loop back around to the first element.
If you intended to have the elements reveal themselves in sequence and not hide earlier ones, just get rid of the .removeClass('showing') line:
$(document).ready(function() {
$('button.one').click(function() {
$('.showing') // find the current element
.next() // find its next sibling
.addClass('showing'); // show that
if ($('.showing').length === 0) {
// nothing is showing, so show the first one
$('#page1 div:eq(0)').addClass('showing')
}
})
})
#page1 div {height: 10px}
#page1 div.showing {background-color: red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="one">Click Me!</button>
<div id="page1">
<div class="panel1"></div>
<div class="panel2"></div>
<div class="panel3"></div>
<div class="panel4"> </div>
</div>
What you can do is count the amount of children that you have, and compare the amount of clicks through a given iterator you have to see what should be shown.
I added an extra functionality that hides the elements again once the max amount of divs has been shown.
Hope this helps.
$(document).ready(function() {
$('#page1').children().each(function () {
$(this).hide();
});
});
var panel="panel";
var pannelNum=0;
var count = $("#page1").children().length;
$(".one").on( "click", function() {
pannelNum=pannelNum+1;
if(pannelNum > count) {
$('#page1').children().each(function () {
$(this).hide();
});
pannelNum=0;
}
else {
clicked=panel+""+pannelNum;
$('.'+clicked).show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="one">Click Me!</button>
<div id="page1">
<div class="panel1">
this is panel 1!
</div>
<div class="panel2">
this is panel 2!
</div>
<div class="panel3">
this is panel 3!
</div>
<div class="panel4">
this is panel 4!
</div>
</div><!-- page one -->
<div id="trial">
</div>

Image filter with javascript

I am new to web development. I am trying to create my photography webpage. I have created a basic html design.
I want to filter the image when the specific button is clicked. I went through the w3schools code about it but could not get quite clear about it. Not with the JQuery.
Here is my html code with buttons.
Thank you
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gallery</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<script src="script.js"></script>
<div id="myBtnContainer">
<button class="btn active" onclick="filterSelection('all')">ALL</button>
<button class="btn active" onclick="filterSelection('all')">Nature</button>
<button class="btn active" onclick="filterSelection('all')">Animal</button>
</div>
<!--grid-->
<div class="row">
<div class="column_nature">
<div class="content">
<img src="images/nature.jpg" style="width:40%">
<h4>Nature</h4>
<p>This is me</p>
</div>
</div>
</div>
<div class="column_nature">
<div class="content">
<img src="images/swan.jpg" style="width:40%">
<h4>Swan</h4>
</div>
</div>
</body>
</html>
Because both of your images had 'nature' on them, a filter would not have had any effect. I adapted your code to the w3schools example, but changed it so that the first image had 'nature' as a filter , and the second had 'bird' as a filter.
Incidentally, there is no underscore between the column and the filter name (If you put one in, as you did in your code) it won't work. I adapted this too.
Best of luck
/*this goes in your script.js*/
filterSelection("all") // Execute the function and show all columns
function filterSelection(c) {
var x, i;
x = document.getElementsByClassName("column");
if (c == "all") c = "";
// Add the "show" class (display:block) to the filtered elements, and remove the "show" class from the elements that are not selected
for (i = 0; i < x.length; i++) {
w3RemoveClass(x[i], "show");
if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
}
}
// Show filtered elements
function w3AddClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
if (arr1.indexOf(arr2[i]) == -1) {
element.className += " " + arr2[i];
}
}
}
// Hide elements that are not selected
function w3RemoveClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
while (arr1.indexOf(arr2[i]) > -1) {
arr1.splice(arr1.indexOf(arr2[i]), 1);
}
}
element.className = arr1.join(" ");
}
// Add active class to the current button (highlight it)
var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function(){
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
/*this bit will go into your style.css file*/
* {
box-sizing: border-box;
}
body {
background-color: #f1f1f1;
padding: 20px;
font-family: Arial;
}
/* Center website */
.main {
max-width: 1000px;
margin: auto;
}
h1 {
font-size: 50px;
word-break: break-all;
}
.row {
margin: 8px -16px;
}
/* Add padding BETWEEN each column (if you want) */
.row,
.row > .column {
padding: 8px;
}
/* Create three equal columns that floats next to each other */
.column {
float: left;
width: 33.33%;
display: none; /* Hide columns by default */
}
/* Clear floats after rows */
.row:after {
content: "";
display: table;
clear: both;
}
/* Content */
.content {
background-color: white;
padding: 10px;
}
/* The "show" class is added to the filtered elements */
.show {
display: block;
}
/* Style the buttons */
.btn {
border: none;
outline: none;
padding: 12px 16px;
background-color: white;
cursor: pointer;
}
/* Add a grey background color on mouse-over */
.btn:hover {
background-color: #ddd;
}
/* Add a dark background color to the active button */
.btn.active {
background-color: #666;
color: white;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gallery</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<script src="script.js"></script>
<div id="myBtnContainer">
<button class="btn active" onclick="filterSelection('all')">ALL</button>
<button class="btn active" onclick="filterSelection('nature')">Nature</button>
<button class="btn active" onclick="filterSelection('bird')">Animal</button>
</div>
<!--grid-->
<div class="row">
<div class="column nature">
<div class="content">
<img src="https://images.pexels.com/photos/257360/pexels-photo-257360.jpeg" style="width:40%">
<h4>Nature</h4>
<p>This is me</p>
</div>
</div>
</div>
<div class="column bird">
<div class="content">
<img src="https://www.phrases.org.uk/images/swan-song-1.jpg" style="width:40%">
<h4>Swan</h4>
</div>
</div>
</body>
</html>
I understand that you're new to programming; so beware that some users may provide you with answers suggesting you install jQuery, or Bootstrap - which while that it entirely true and what I would recommend - I equally understand that these all provide steep learning curves for a beginner.
As such, you can develop in HTML, CSS, and the naked JavaScript library as standard. So I have provided a solution to your problem in the code below, and documented my code also, so that you may better understand it.
Replace your code, with my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gallery</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<script src="script.js"></script>
<div id="myBtnContainer">
<button class="btn active" onclick="filterSelection('All')">ALL</button>
<button class="btn active"
onclick="filterSelection('Nature')">Nature</button>
<button class="btn active"
onclick="filterSelection('Swan')">Animal</button>
</div>
<!--grid-->
<div class="row">
<div class="column_nature filter" id="Nature">
<div class="content">
<img src="images/nature.jpg" style="width:40%">
<h4>Nature</h4>
<p>This is me</p>
</div>
</div>
</div>
<div class="column_nature filter" id="Swan">
<div class="content">
<img src="images/swan.jpg" style="width:40%">
<h4>Swan</h4>
</div>
</div>
</div>
<script>
// Function to hide all other elements, bar the parameter provided
function filterSelection(elementToShow){
if(elementToShow != "All"){
// Get an array of elements with the class name, filter.
var x = document.getElementsByClassName("filter");
// For each of them
for(var i = 0; i < x.length; i++){
// Make them invisible
x[i].style.display = "none";
}
// Get and then make the one you want, visible
var y = document.getElementById(elementToShow).style.display = "block";
}
else{ // If the parameter provided is all, we want to display everything
// Get an array of elements with the class name, filter.
var x = document.getElementsByClassName("filter");
// For each of them
for(var i = 0; i < x.length; i++){
//Make them visible
x[i].style.display = "block";
}
}
}
</script>
</body>
</html>
Please note the following; if you add a new button to filter something else, you must give it an * onclick="filterSelection('x')" * where the x is the name of that which you want to filter. Then on the div you want to keep, simply give it a class with the same name as "x".
So for instance, if I had a button:
<button onclick="filterSelection('Mountains')">Mountains</button>
Then I would expect that if I click it, that all filter class divs would be hidden, except for the div that had the class mountains. So I would have to have a div like so:
<div class="filter Mountains">This would be the div that would be displayed on click of the above button, and all others would be hidden.</div>
I hope this helps provide you with the answer you were looking for, although eventually it would be best to look into Bootstrap or jQuery which will be much more sustainable in the long run.

How to set focus on div-wrapped siblings with jQuery?

Due to requirements beyond my control (no mouse), I need to be able to use the arrow keys (in addition to tab) to scroll up and down through a stack of buttons on a web page.
I figured out how to do it with buttons that are pure siblings, but if I wrap those buttons in divs (to stack them vertically), my jQuery selector no longer works. I essentially need a selector for "my parent's next sibling's child". I have beaten my head against the wall for hours and can't figure this out.
In the following example, if you set focus to one of the buttons on the bottom, the arrow keys will let you move between the buttons. The top pair of buttons, however, are wrapped in divs and the arrow keys won't work there.
Help?
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/button/index">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.material.mobile.min.css" />
<script src="https://kendo.cdn.telerik.com/2017.3.913/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.3.913/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example">
<div class="demo-section k-content">
<div>
<p>
This doesn't work with up/down arrow keys:
<div><button id="textButton1" tabIndex="0">Button 1</button></div>
<div><button id="textButton2" tabIndex="0">Button 2</button></div>
</p>
<p>
But this does:
<button id="textButton3" tabIndex="0">Button 3</button>
<button id="textButton4" tabIndex="0">Button 4</button>
</p>
</div>
<script>
$(document).ready(function () {
$("#textButton1").kendoButton();
$("#textButton2").kendoButton();
$("#textButton3").kendoButton();
$("#textButton4").kendoButton();
$(".k-button").width(350);
$(".k-button:first").focus();
});
document.addEventListener('keydown', function(event)
{
const key = event.key;
switch (key)
{
case "ArrowDown":
//alert('Down');
$(".k-button:focus").next().focus();
break;
case "ArrowUp":
//alert('Up');
$(".k-button:focus").prev().focus();
break;
}
});
</script>
<style>
.demo-section p {
margin: 0 0 30px;
line-height: 50px;
}
.k-button {
margin-bottom: 20px;
}
.k-button .k-icon {
float: right;
margin: 2px;
}
</style>
</div>
</body>
</html>
as you are working with ID's I made this example you can try it.
I didn't work with next and previous but I added a data-key to each button.
hope it helps you
$(document).ready(function () {
$("#textButton1").kendoButton();
$("#textButton2").kendoButton();
$("#textButton3").kendoButton();
$("#textButton4").kendoButton();
$(".k-button").width(350);
$(".k-button:first").focus();
});
document.addEventListener('keydown', function(event)
{
const key = event.key;
switch (key)
{
case "ArrowDown":
indexKey = $(".k-button:focus").data('key')+1
$('#textButton'+indexKey).focus();
break;
case "ArrowUp":
indexKey = $(".k-button:focus").data('key')-1
$('#textButton'+indexKey).focus();
break;
}
});
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/button/index">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.material.mobile.min.css" />
<script src="https://kendo.cdn.telerik.com/2017.3.913/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.3.913/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example">
<div class="demo-section k-content">
<div>
<p>
This doesn't work with up/down arrow keys:
<div><button id="textButton1" data-key='1' tabIndex="0">Button 1</button></div>
<div><button id="textButton2" data-key='2' tabIndex="0">Button 2</button></div>
</p>
<p>
But this does:
<button id="textButton3" data-key='3' tabIndex="0">Button 3</button>
<button id="textButton4" data-key='4' tabIndex="0">Button 4</button>
</p>
</div>
<style>
.demo-section p {
margin: 0 0 30px;
line-height: 50px;
}
.k-button {
margin-bottom: 20px;
}
.k-button .k-icon {
float: right;
margin: 2px;
}
</style>
</div>
</body>
</html>
As you know, next() or prev() only works with siblings. For your case, you could use button indexes instead...
document.addEventListener('keydown', function(event) {
const key = event.key;
var lastButtonIndex = $(".k-button").length - 1;
var focusedButtonIndex = $(".k-button").index($(".k-button:focus"));
switch (key) {
case "ArrowDown":
if (focusedButtonIndex < lastButtonIndex)
$(".k-button").eq(focusedButtonIndex+1).focus();
break;
case "ArrowUp":
if (focusedButtonIndex > 0)
$(".k-button").eq(focusedButtonIndex-1).focus();
break;
}
});
I hope it helps

Categories

Resources