Using one function for two images - javascript

Consider the following markup
<div class="like-buttons">
<img src="up.png" onclick="onClick()" />
<span id="clicks">0</span>
<img src="down.png" onclick="onClick()" />
</div>
And the following JavaScript function
<script type="text/javascript">
var clicks = 0;
function onClick() {
if (clicks < 10) {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
} else {
document.getElementById("clicks").innerHTML = clicks;
}
};
</script>
Now what I'm trying to achieve is that when Up image is clicked the count goes up by 1 to a max of 10 and when down is clicked the count to go down by 1 and shouldn't go below 0. Currently the count goes up but I was wondering is there a way which I can add an event for each image in the same function or would I have to write two separate functions one for each image?
Thanks in advance for your help

call onClick() function with param, e.g. onClick(1) (for up button) and onClick(-1) for down button.
function onClick(value) {
var clicks = parseInt(document.getElementById("clicks").innerHTML);
clicks += value;
if (clicks > 10)
clicks = 10;
if (clicks < 0)
clicks = 0;
document.getElementById("clicks").innerHTML = clicks;
}

<div class="like-buttons">
<img src="up.png" onclick="onClick(plus)" />
<span id="clicks">0</span>
<img src="down.png" onclick="onClick(min)" />
</div>
<script type="text/javascript">
var clicks = parseInt(document.getElementById("clicks").innerHTML);
function onClick(type){
if (type=='plus' && clicks < 10) {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
} else {
if (clicks > 0) clicks -= 1;
document.getElementById("clicks").innerHTML = clicks;
}
};

var clicks = 0;
function onClick(element) {
var imge = element.src;
if (clicks < 10 && imge.indexOf('up.png') != -1) {
clicks++;
} else if(clicks >0 && imge.indexOf('down.png') != -1) {
clicks--;
}
document.getElementById("clicks").innerHTML = clicks;
};
<div class="like-buttons">
<img src="up.png" onclick="onClick(this)" />
<span id="clicks">0</span>
<img src="down.png" onclick="onClick(this)" />
</div>

adding logic to #bhushans ans to complete the requirement when Up image is clicked the count goes up by 1 to a max of 10 and when down is clicked the count to go down by 1 and shouldn't go below 0.
fiddle
<div class="like-buttons">
<img src="up.png" onclick="onClick(true)" /> <span id="clicks">0</span>
<img src="down.png" onclick="onClick(false)" />
</div>
and js should be
var clicks = 0;
function onClick(flag) {
if (flag) {
if (clicks < 10) {
clicks += 1;
} }else{
if (clicks > 0) {
clicks -= 1;
}
}
document.getElementById("clicks").innerHTML = clicks;
}

You can use the same function as the event handler for both images. Just check the id of the event object to check whether to add or subtract.
Example Snippet:
var result = 0,
img1 = document.getElementById('i1'),
img2 = document.getElementById('i2'),
span = document.getElementById('clicks');
img1.addEventListener('click', calc);
img2.addEventListener('click', calc);
function calc(e) {
var img = e.target;
result = img.id == 'i1' ? (result+1) : (result-1);
result = result < 0 ? 0 : result > 10 ? 10 : result;
span.textContent = result;
}
img { cursor: pointer; margin: 5px; vertical-align: middle; }
<div class="like-buttons">
<img id='i1' src="//placehold.it/32x32?text=Up" title="Up" />
<span id="clicks">0</span>
<img id='i2' src="//placehold.it/32x32/?text=Dn" title="Down" />
</div>

You can try this : As Johan commented, pass flag. Flag could be true / false or up /down or anything you want which will identify that which button clicked (up or down).
See below code
var clicks = 0;
function onClick(flag) {
if(flag && clicks < 10)
clicks += 1;
else if(!flag && clicks > 0)
clicks -= 1;
document.getElementById("clicks").innerHTML = clicks;
};
<div class="like-buttons">
<img src="up.png" onclick="onClick(true)" />
<span id="clicks">0</span>
<img src="down.png" onclick="onClick(false)" />
</div>

Have a look at this snippet if can be a better solution, in order to have multiple images and same result. I've also added a 0 control for -1
$(document).ready(function(){
$('.up').click(function() {
var clicks = parseInt($(this).parent().find('.clicks').html());
clicks = clicks +1
if(clicks == 10) {
$(this).hide();
}
$(this).parent().find('.clicks').html(clicks);
});
$('.down').click(function() {
var clicks = parseInt($(this).parent().find('.clicks').html());
if(clicks > 0) {
clicks = clicks - 1
}
if(clicks < 10) {
$(this).parent().find('.up').show()
}
$(this).parent().find('.clicks').html(clicks);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="like-buttons">
<button type="button" class="up">+1</button>
<span class="clicks">0</span>
<button type="button" class="down">-1</button>
</div>
<div class="like-buttons2">
<button type="button" class="up">+1</button>
<span class="clicks">0</span>
<button type="button" class="down">-1</button>
</div>

Related

javascript slider with thumbnail not working with both options

I make an image slider with text and thumbnail as well.
the issue is when I click the thumbnail its shows the photo correctly no issue but when I click the next button then click on the thumbnail then slider not working below is the code.
I used two arrays
for images
for text
then the next() and Previous() function to change the image when clicking on the next and previous button.
var images = ['<img src="images/1.jpg"width = 100%; height=500px; >',
'<img src="images/2.jpg"width = 100%; height=500px; >',
'<img src="images/3.jpg" width = 100%; height=500px;>'
];
var text = ["Missing From Karachi", "Missing From Peshawer", "Missing From Lahore"];
var i = 0;
var x = document.getElementById("demo");
var y = document.getElementById("text");
function next() {
i++;
if (i < images.length) {
x.innerHTML = images[i];
y.innerHTML = text[i];
} else {
i = 0;
x.innerHTML = images[i];
y.innerHTML = text[i];
}
}
function prev() {
i--;
if (i >= 0) {
x.innerHTML = images[i];
y.innerHTML = text[i];
} else {
i = images.length - 1;
x.innerHTML = images[i];
y.innerHTML = text[i];
}
}
function thumbchange(num) {
var thumb = 'images/' + num + '.jpg';
document.getElementById("demo1").src = thumb;
}
<div class="slider">
<p class="text" id="demo"><img id="demo1" src="images/1.jpg" width=100%; height=500px;> </p>
<div class="onebtn">
<button id="btn1" class="btn1 btn btn-primary btn-lg" type="button" class="prev" onclick="prev()">PREVIOUS</button>
</div>
<div class="twobtn">
<button id="btn2" class="btn2 btn btn-primary btn-lg" type="button" class="next" onclick="next()">NEXT</button>
</div>
<p id="text" class="text" style="font-size:40px; font-weight:bolder;">Missing From Karachi</p>
<br><br>
<ul class="thumbs">
<li class="img12" onclick="thumbchange(1)"><img src="images/1.jpg" width=100%;></li>
<li class="img12" onclick="thumbchange(2)"><img src="images/2.jpg"></li>
<li class="img12" onclick="thumbchange(3)"><img src="images/3.jpg"></li>
</ul>
</div>
see the example
https://codepen.io/pen/?template=WNxebOO

Call javascript to preserve filter state when traverse from other page via href

I have a number of webpages in a report each page has a checbox filter that if selected calls javascript to show hide some elements of the page, the checkbox filter enables to true, all pages are created in advance. The user can traverse from one pages by clocking on a url .
The trouble is because the pages are created in advance the filter always default to true, even if just set to false by user on previous page. I think I need to call some javascript to set the value of the filter to the value of the filter on the calling page but because traversing form page to page via a hyperlink I dont know how to call the Javascript.
FYI
Html Filter
<div class="mb-2">
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" name="showLabels" id="showLabels" checked="checked" onclick="toggleLabelsFilter('showLabels');">
<label for="showLabels" id="showLabelslabel" class="form-check-label">
Show Labels
</label>
</div>
</div>
Example html that will have elements hidden
<figure class="figure" style="position:relative">
<a href="StatusReport00017_byfolder00021.html">
<img src="../images/E__Melco_TestMusic_WAV_WAV_Antonin Dvorak; Itzhak Perlman, Daniel Barenboim, Samuel Sanders.jpg" class="figure-img" width="200" height="200">
</a>
<div style="position:absolute; top:144px;">
<div class="badge ml-2 badge-primary">
12 files
</div>
</div>
<div style="position:absolute; top:166px;">
<div class="badge ml-2 badge-success">
12 MB
</div>
<div class="badge ml-2 badge-warning">
0 Discogs
</div>
</div>
<figcaption class="figure-caption">
<a href="StatusReport00017_byfolder00021.html">
Antonin Dvorak; Itzhak Perlman, Daniel Barenboim, Samuel Sanders
</a>
</figcaption>
</figure>
Javascript
function toggleLabelsFilter(filterName)
{
var checkbox = document.getElementById(filterName);
if(checkbox.checked)
{
var badges = document.getElementsByClassName("badge");
for (i = 0; i < badges.length; i++)
{
badges[i].style.visibility = "visible";
}
}
else
{
var badges = document.getElementsByClassName("badge");
for (i = 0; i < badges.length; i++)
{
badges[i].style.visibility = "hidden";
}
}
}
Edit Update
Attempt based on comments
Called when user selects checkbox
function toggleLabelsFilter()
{
var checkbox = document.getElementById("showLabels");
if(checkbox.checked)
{
sessionStorage.setItem("showLabels", true);
var badges = document.getElementsByClassName("badge");
for (i = 0; i < badges.length; i++)
{
badges[i].style.visibility = "visible";
}
}
else
{
sessionStorage.setItem("showLabels", false);
var badges = document.getElementsByClassName("badge");
for (i = 0; i < badges.length; i++)
{
badges[i].style.visibility = "hidden";
}
}
}
Called when page loaded
function checkFilter()
{
if(sessionStorage.getItem("showLabels")==true)
{
document.getElementById("showLabels").checked=true;
var badges = document.getElementsByClassName("badge");
for (i = 0; i < badges.length; i++)
{
badges[i].style.visibility = "visible";
}
}
else
{
document.getElementById("showLabels").checked=false;
var badges = document.getElementsByClassName("badge");
for (i = 0; i < badges.length; i++)
{
badges[i].style.visibility = "hidden";
}
}
}

html-JavaScript- when switching to next div only displays for a split second then disappears

Here is my function. I want to switch from one div to another. I am getting this to happen but only for a quick second then it returns back to the first div.
function NextDiv()
{
var div = document.querySelectorAll("#div0>div");
for (var i = 0; i < div.length; i++)
{
if (div[i].style.display != "none")
{
div[i].style.display = "none";
if (i == div.length - 1)
{
div[0].style.display = "block";
}
else
{
div[i + 1].style.display = "block";
}
return false;
}
}
}
here is a testable fiddle: https://jsfiddle.net/pnumtc35/5/
at the line where you do div[i+1] the new div gets shown. but on the next iteration of your for-loop it get immediately hidden again. Thats why i added a break to stop the loop.
function NextDiv()
{
console.log('click');
var div = document.querySelectorAll("#div0>div");
for (var i = 0; i < div.length; i++)
{
if (div[i].style.display != "none")
{
div[i].style.display = "none";
if (i == div.length - 1)
{
div[0].style.display = "block";
}
else
{
div[i + 1].style.display = "block";
break; // ADDED
}
}
}
}
<div id="div0">
<div class="column" id="div1" >
<h2>Customer Information </h2>
<button runat="server" id="nextbutton" onclick="NextDiv()" >Next </button>
</div>
<div class="column" id="div2" style="display: none;">
<h2>Payment Information</h2>
<button runat="server" id="Button1" onclick="NextDiv()">Next </button>
</div>
<div class="column" id="div3" style="display: none;">
<h2>Shipment Information</h2>
<Button ID="btn1" runat="server" Text="Save" onclick="SaveInfo"/>
</div>
</div>

setTimeOut for button cliks in javascript

I'm trying to make it so the user cannot press a number button until the start button is pressed. I've searched w3schools and other sites, but cannot find a solution. Any help would be appreciated, even if you can point me to a website. My instructor has informed use that we would need to find any solutions to our problems online. Even suggestions for a good javascript book would be helpful as there is no text book for the class and he doesn't teach it.
<body>
<h3 style="margin-left: 15px">This is Your TARGET:</h3>
<div id="randomNum" class="display" style="margin-top: -20px; margin-bottom: 30px">0</div>
<!-- Start button -->
<button onclick="setTimeout(myFunction, 5000);">Start</button>
<!-- Total value text -->
<div id="text_total">0</div>
<!-- Number buttons -->
<div class="number_button" onclick="change_total(1)">1</div>
<div class="number_button" onclick="change_total(2)">2</div>
<div class="number_button" onclick="change_total(3)">3</div>
<div class="number_button" onclick="change_total(4)" style="clear: left">4</div>
<div class="number_button" onclick="change_total(5)">5</div>
<div class="number_button" onclick="change_total(6)">6</div>
<div class="number_button" onclick="change_total(7)" style="clear: left; margin-bottom: 30px">7</div>
<div class="number_button" onclick="change_total(8)" style="margin-bottom: 30px">8</div>
<div class="number_button" onclick="change_total(9)" style="margin-bottom: 30px">9</div>
<h3 style="clear: left; margin-left: 58px">COUNTER!</h3>
<div id="counter" class="display" style="clear: left; margin-top: -20px">0</div>
<script>
// Variables
var total = 0;
var target;
var clicks = 0;
window.onload = randomNumber();
// Functions
function change_total(arg) { // This takes button input and changes the total value
total = total + arg;
clicks = clicks + 1;
update_total();
if (total == target) {
alert("You win!"); // popup window with message
total = 0; // reset for next round
clicks = 0; // resets the click counter
randomNumber(); //gets new number for next round
update_total();
}if (total > target) {
alert("BUSTED!!");
total = 0;
clicks = 0;
randomNumber();
update_total();
}
update_clicks();
}
function myFunction() {
alert("You failed to reach the target in time!");
}
function update_total() { // Updates the text on the screen to show the current total
document.getElementById("text_total").innerHTML = total;
}
function randomNumber() { // returns a random number between 25 and 75
target = Math.floor(Math.random() * (50) + 25);
document.getElementById("randomNum").innerHTML = target;
}
function update_clicks() { // lets user know how many clicks
document.getElementById("counter").innerHTML = "You clicked the mouse " + clicks + " times.";
}
</script>
</body>
You may try for this,
I have tested it on my end, see below,
i just use isStart boolean variable to check is game start or not.
<body>
<h3 style="margin-left: 15px">This is Your TARGET:</h3>
<div id="randomNum" class="display" style="margin-top: -20px; margin-bottom: 30px">0</div>
<!-- Start button -->
<button onclick="startGame()">Start</button>
<!-- Total value text -->
<div id="text_total">0</div>
<!-- Number buttons -->
<div class="number_button" onclick="change_total(1)">1</div>
<div class="number_button" onclick="change_total(2)">2</div>
<div class="number_button" onclick="change_total(3)">3</div>
<div class="number_button" onclick="change_total(4)" style="clear: left">4</div>
<div class="number_button" onclick="change_total(5)">5</div>
<div class="number_button" onclick="change_total(6)">6</div>
<div class="number_button" onclick="change_total(7)" style="clear: left; margin-bottom: 30px">7</div>
<div class="number_button" onclick="change_total(8)" style="margin-bottom: 30px">8</div>
<div class="number_button" onclick="change_total(9)" style="margin-bottom: 30px">9</div>
<h3 style="clear: left; margin-left: 58px">COUNTER!</h3>
<div id="counter" class="display" style="clear: left; margin-top: -20px">0</div>
<script>
// Variables
var total = 0;
var target;
var clicks = 0;
window.onload = randomNumber();
var isStart=false;
// Functions
function change_total(arg) { // This takes button input and changes the total value
if(isStart){
total = total + arg;
clicks = clicks + 1;
update_total();
if (total == target) {
alert("You win!"); // popup window with message
total = 0; // reset for next round
clicks = 0; // resets the click counter
randomNumber(); //gets new number for next round
update_total();
isStart=false;
}if (total > target) {
alert("BUSTED!!");
total = 0;
clicks = 0;
randomNumber();
update_total();
isStart=false;
}
update_clicks();
}
else{
alert('please start the game');
}
}
function myFunction() {
alert("You failed to reach the target in time!");
}
function update_total() { // Updates the text on the screen to show the current total
document.getElementById("text_total").innerHTML = total;
}
function randomNumber() { // returns a random number between 25 and 75
target = Math.floor(Math.random() * (50) + 25);
document.getElementById("randomNum").innerHTML = target;
}
function update_clicks() { // lets user know how many clicks
document.getElementById("counter").innerHTML = "You clicked the mouse " + clicks + " times.";
}
function startGame(){
isStart=true;
}
</script>
</body>

How to show a div1 div2 div3 div4 div5 using html input button1 button2 button3 button4 button5

I have 5 div tag and 5 html input button also, i want to select/show one div at a time using html input button click.
<script>
$(function () {
// Store our questions in a variable
var $questions = $('.question');
// Show the first question
$questions.first().show();
// When clicking the <button> in ny of the questions...
$questions.find('input').on('click', function () {
// ...store the currently visible question, then...
var $visibleQuestion = $questions.filter(':visible');
// ...if there's a next question....
var $nextQuestion = $visibleQuestion.next('.question');
console.log($nextQuestion);
if ($nextQuestion.length === 1) {
// ...hide the visible question....
$visibleQuestion.hide();
// ..and show the next.
$nextQuestion.show();
}
// If you want, you can check for quiz completition in this else section
else {
// Quiz finished
alert('You finished the quiz!');
}
});
// Optionally, change the text of the last question's button
$questions.last().find('input').text('Finish Quiz');
});
</script>
<script type="text/javascript">
var x, y;
var i = 0;
var j = 0;
for (x = 0; x < 20; x++) {
for (y = 0; y < 5; y = y + 1) {
document.write('<input id="button' + (i + 1) + '" class="btnClass" type="button" value="' + (i + 1) + '" style="width:30px; height:25px;text-align:left;" />');
i++;
document.write('&nbsp &nbsp');
if (i % 5 == 0) {
document.write('<br /> <br />');
}
}
}
</script>
There are 5 divs which are initially hidden and display when clicked on the button.
$(document).ready(function()
{
$("#btn2").click(function()
{
$("#two").removeClass("hidden");
});
});
$(document).ready(function()
{
$("#btn3").click(function()
{
$("#three").removeClass("hidden");
});
});
$(document).ready(function()
{
$("#btn4").click(function()
{
$("#four").removeClass("hidden");
});
});
$(document).ready(function()
{
$("#btn5").click(function()
{
$("#five").removeClass("hidden");
});
});
<body>
<style type="text/css">
.hidden
{
visibility:hidden;
}
</style>
<button id="btn1">DIV 1</button>
<button id="btn2">DIV 2</button>
<button id="btn3">DIV 3</button>
<button id="btn4">DIV 4</button>
<button id="btn5">DIV 5</button>
<div id='one' class="hidden">1 Lorem </div>
<div id="two" class="hidden">2 lorem</div>
<div id="three" class="hidden">3 lorem </div>
<div id="four" class="hidden">4 lorem </div>
<div id="five" class="hidden">5 lorem </div>

Categories