I have a two part problem I am wanting to create a game of rock,paper scissors, that allows the user to play until he loses once against the computer. I will show the user a series of images (rock,paper,scirssors). I will then highlight the choice if the user clicks the image, then double click to confirm their choice to play against.
So I have this in my HTML that is shown after the user clicks play now:
<div id="playOptionsclassic" style="display: none">
<img id="clickedRock" src="img/rock.jpg" onclick="playClassicWithRock()" dis/>
<img id="clickedPaper" src="img/paper.jpg" onclick="playClassicWithPaper()"/>
<img id="clickedScissors" src="img/scissors.jpg" onclick="playClassicWithScissors()" />
</div>
Then in my Jquery file I have:
$(function () {
$("img").one("click",function() {
$(this).css('border', "solid 2px red");
});
});
The problem I have here is the user can click more then one img right now. I want it to toggle the click, so if I click rock first, oh I change my mind I want scissors, unhighlight rock and highlight scissors. Or should i just make so it's one click and it is locked in?
How can I then pass a value of "rock","Paper" Scissors" into a javascript file to see if they beat the computer?
Use $(this).siblings().css('border','0px') for change the colors of the clicked item and use playClassicWithScissors(this) "this" to pass your element to the function
$(function () {
$("img").on("click",function() {
$(this).siblings().css('border','0px')
$(this).css('border', "solid 2px red");
});
});
function playClassicWithRock(ele){
alert($(ele).attr('id'));
}
function playClassicWithPaper(ele){
alert($(ele).attr('id'));
}
function playClassicWithScissors(ele){
alert($(ele).attr('id'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="playOptionsclassic" style="display: block">
<img id="clickedRock" src="img/rock.jpg" onclick="playClassicWithRock(this)" dis/>
<img id="clickedPaper" src="img/paper.jpg" onclick="playClassicWithPaper(this)"/>
<img id="clickedScissors" src="img/scissors.jpg" onclick="playClassicWithScissors(this)" />
</div>
First of all, you should prefer to use classes to individual CSS styles. It is generally easier (and much more robust, maintenance-wise) to add and strip a class, than to adjust the CSS properties.
An easy way to do this is to find a selector that matches all three images; then you can strip the "selected" class from all images (whether they have it or not) before you add it to the clicked image. jQuery makes this very easy.
The other typical way is to store the selection, so you can explicitly deselect that element before selecting a new one.
<div id="playOptionsclassic" style="display: none">
<img id="clickedRock" src="img/rock.jpg" class="game-opt-img" data-val="rock" dis/>
<img id="clickedPaper" src="img/paper.jpg" class="game-opt-img" data-val="paper"/>
<img id="clickedScissors" src="img/scissors.jpg" class="game-opt-img" data-val="scissors" />
</div>
Then in your javascript
$(function(){
$(".game-opt-img").on("click", function() {
$(".game-opt-img").off("click"); // remove all image's click event
var val = $(this).data("val"); // get the value of the image that the user choose.
});
});
You can create a class in css called .active which adds the border to the image. So, when you click on an image, all you need to do is remove the .active class from all the images, and then add the .active to the image you clicked on.
This can be achieved by doing the following:
$(function() {
$("#playOptionsclassic div").on("click", function() {
$("#playOptionsclassic div").removeClass('active');
$(this).addClass('active');
});
});
.active {
border: 2px solid red;
}
/* Styles for example */
#playOptionsclassic div {
height: 100px;
width: 100px;
background: black;
color: white;
margin: 1%;
display: inline-block;
text-align: center;
box-sizing: border-box;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="playOptionsclassic">
<!-- Images replaced with divs for example -->
<div id="clickedRock">Rock img</div>
<div id="clickedPaper">Paper img</div>
<div id="clickedScissors">Scissors img</div>
</div>
First you can add a predefined class to each of the images and assign them a data attribute for what they represent (rock, paper, scissors) as follows:
<div id="playOptionsclassic" style="display: none">
<img class="option" src="img/rock.jpg" data-option="rock"/>
<img class="option" src="img/paper.jpg" data-option="paper"/>
<img class="option" src="img/scissors.jpg" data-option="scissors"/>
</div>
Then you can create a class in CSS where you will have the style of the clicked image:
.active {
border: 2px solid red;
}
And in your javascript, when the user single clicks one of the options, remove the active class from the others and add it to that image.
And when they double click, check if an option was selected and perform the necessary actions.
$(function() {
$("img.option").on("click", function() {
$("img.option.active").removeClass("active");
$(this).addClass("active");
});
$("img.option").on("dblclick", function() {
var selectedOption = $("img.option.active");
// Check if an option was selected.
if (selectedOption.length) {
// Save the name of the option (rock, paper or scissors) in a variable.
var optionName = selectedOption.data("option");
// Perform your action here.
} else {
alert("Please select an option.");
}
});
});
Related
My motive is when someone will click on a particular button then will show the particular cards and will add a class named category_btn_active that clicked. Suppose Services will be clicked then the service cards will be shown. Here the filtering is working well, the problem is here $(this).addClass('category_btn_active').siblings().removeClass('category_btn_active'). The category_btn_active class adds when clicked but when I clicked another button it stays in both buttons. I want the class will be added to just the last clicked button. Where is the problem? give a relevant solution...
index.html:
<li>Services</li>
<li>Static Website</li>
<div class="Services service_itembox">
<img src="Assets/pic-1.jpg" alt="service image">
</div>
<div class="Static service_itembox">
<img src="Assets/pic-2.jpg" alt="service image">
</div>
index.js:
$(function () {
$(".category_btn").click(function () {
$(this).addClass('category_btn_active').siblings().removeClass('category_btn_active')
const value = $(this).attr('data-filter');
if(value == "Services"){
$('.service_itembox').show('slow');
}else{
$('.service_itembox').not('.'+value).hide('slow');
$('.service_itembox').filter('.'+value).show('slow');
}
});
});
style.css:
.category_btn_active{
color: white;
border-color:gray;
border-style:solid ;
border-width:0px 0px 1px 0px;
background-color: #019587;
padding: 8px;
font-size: 14px;
text-transform: uppercase;
}
This is not the most elegant way to do this, but it illustrates use of parent() and sibling(), which you were struggling with:
https://jsfiddle.net/v5fg3qwh/2/
$(function () {
$(".category_btn").click(function () {
$(this).addClass('category_btn_active').parent().siblings().find("a.category_btn").removeClass('category_btn_active')
const value = $(this).attr('data-filter');
$(`.${value}.service_itembox`).show('slow');
$(`.service_itembox`).not('.'+value).hide('slow');
$(`.service_itembox`).filter('.'+value).show('slow');
});
});
Note that I removed your if/else because you don't need it. Your classes and JS logic are defined in such a way that you can specify your intent w/out those conditionals.
I also defaulted one of your images to be hidden at initialization, which I assume is what you'd want:
div.Static.service_itembox {
display: none;
}
I have a function that changes the src attribute of an icon when this one is clicked.
I also want it to hide the closest icon of the class fave_icon. I tried the following but it's not working:
function trash(event, trashcan){
event.stopPropagation();
if (trashcan.getAttribute('src') == "Iconos/tacho.png")
{
trashcan.src = "Iconos/warning.png"; //this works ok
var heart = trashcan.closest(".fave_icon");
heart.style.visibility = "hidden"
}
}
Basically I want to hide the closest element with class fave_icon to trashcan.
On the HTML I have this several times:
<button class="accordion">
<div>
<img src="Iconos/heart.png" onclick="fav(event,this);" alt="Fave" class="fave_icon">
</div>
<div>
<img src="Iconos/tacho.png" onclick="trash(event,this);" alt="Delete" class="delete_icon">
</div>
</button>
If fave_icon is a class then you have to place dot (.) before the class name as part of the selector.
Change var heart = trashcan.closest("fave_icon");
To
var heart = trashcan.closest(".fave_icon");
Based on the code and HTML you have provided you can do something like the following:
function trash(event, trashcan){
event.stopPropagation();
if (trashcan.getAttribute('src') == "Iconos/tacho.png"){
trashcan.src = "Iconos/warning.png"; //this works ok
var heart = trashcan.closest('button').querySelector('.fave_icon');
heart.style.visibility = "hidden";
}
}
<button class="accordion">
<div>
<img src="Iconos/heart.png" onclick="fav(event,this);" alt="Fave" class="fave_icon">
</div>
<div>
<img src="Iconos/tacho.png" onclick="trash(event,this);" alt="Delete" class="delete_icon">
</div>
</button>
From the trash icon, you go up a level to the div, select the previousElementSibling to get the heart's div, and then go down a level to the heart image itself.
Because the element is already included in the event target, you don't need to pass this. Or, even better, if you select the trash image first, you can avoid this entirely and use explicit variable names, which are easier to understand and debug.
But inline event handlers are essentially eval inside HTML markup - they're bad practice and result in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead, eg: https://developer.mozilla.org/en/DOM/element.addEventListener
Another problem is that buttons should not have closing tags. Use a container element instead, like a div.
So, try something like this:
document.querySelectorAll('img[src="Iconos/tacho.png"]').forEach(img => {
img.onclick = () => {
const heartImg = img.parentElement.previousElementSibling.children[0];
heartImg.style.visibility = 'hidden';
};
});
<div class="accordion">
<div>
<img src="Iconos/heart.png" alt="Fave" class="fave_icon">
</div>
<div>
<img src="Iconos/tacho.png" alt="Delete" class="delete_icon">
</div>
</div>
you can add a class to the clicked element and use the general sibling combinator if the two items are adjacent.
document.getElementById("hide")
.addEventListener("click", (event) => {
event.target.classList.add('active');
}, false);
#hide.active~.element {
visibility: hidden;
}
#hide {
cursor: pointer;
}
.accordion {
padding: 15px;
background: lightgrey;
border-bottom: 1px solid grey;
}
.accordion div {
color: black;
margin-right: 20px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/icono/1.3.0/icono.min.css" rel="stylesheet" />
<div class="accordion">
<div class="icono-trash" id="hide"></div>
<div class="element icono-heart"></div>
</div>
I'm trying to make a toggle which works, but every element I click on creates a stack of these showed elements. Instead I'm trying to hide everything and display only element that I clicked on. Now I can only hide it when I click on the same element twice, which is not what I want. I want to click on one and hide previous ones that were showing.
.totalpoll-choice-image-2 is a bunch of images that always has to be shown. They are what the user clicks on to display hidden description under each image. That description shows up when I click on .totalpoll-choice-image-2. There are 5 images with that class. The next image I click on, I want to hide the previous description box.
My code:
jQuery(document).ready(function() {
var element = document.getElementsByClassName("totalpoll-choice-image-2");
var elements = Array.prototype.slice.call(Array.from( element ) );
console.log(elements);
jQuery(element).each(function(item) {
jQuery(this).unbind('click').click(function(e) {
e.stopPropagation();
var id = jQuery(this).attr("data-id");
console.log(this);
//jQuery("#" + id).css({"display": 'block !important'});
//document.getElementById(id).style.setProperty( 'display', 'block', 'important' );
var descriptionContainer = document.getElementById(id);
var thiss = jQuery(this);
console.log(thiss);
console.log(jQuery(descriptionContainer).not(thiss).hide());
jQuery(descriptionContainer).toggleClass("show");
});
})
})
You can attach event handlers to a group of DOM elements at once with jQuery. So in this case, mixing vanilla JS with jQuery isn't doing you any favors - though it is possible.
I threw together this little example of what it sounds like you're going for.
The script itself is very simple (shown below). The classes and IDs are different, but the idea should be the same:
// Assign click handlers to all items at once
$('.img').click(function(e){
// Turn off all the texts
$('.stuff').hide();
// Show the one you want
$('#' + $(e.target).data('id')).show();
})
https://codepen.io/meltingchocolate/pen/NyzKMp
You may also note that I extracted the ID from the data-id attribute using the .data() method, and attached the event listener with the .click() method. This is the typical way to apply event handlers across a group of jQuery objects.
From what I understood based on your comments you want to show only description of image that has been clicked.
Here is my solution
$('.container').on('click', 'img', function() {
$(this).closest('.container').find('.image-description').addClass('hidden');
$(this).siblings('p').removeClass('hidden');
});
https://jsfiddle.net/rtsj6r41/
Also please mind your jquery version, because unbind() is deprecated since 3.0
You can use event delegation so that you only add your event handler once to the parent of your images. This is usually the best method for keeping work the browser has to do down. Adding and removing classes is a clean method for show and hide, because you can see what is happening by looking at your html along with other benefits like being easily able to check if an item is visible with .hasClass().
jsfiddle: https://jsfiddle.net/0yL5zuab/17/
EXAMPLE HTML
< div class="main" >
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="clear">
</div>
</div>
EXAMPLE CSS
.image-parent{
height: 100px;
width: 200px;
float: left;
margin: 5px;
}
.image-parent .image{
background: blue;
height: 50%;
width: 100%;
}
.image-descr{
display: none;
height: 50%;
width: 100%;
}
.show-descr{
display: block;
}
.clear{
clear: both;
}
EXAMPLE JQUERY
$(".main").on("click", ".image-parent", ShowDescription);
function ShowDescription(e) {
var $parent = $(e.target).parent(".image-parent");
var $desc = $parent.find(".image-descr");
$(".image-descr").removeClass("show-descr");
$desc.addClass("show-descr");
}
I have some jquery that will, when a button is clicked, switch a class from a button to a different class (i.e. on click switch class from #testButton from .first to .second with an image toggle to show it works). The first click works well and it toggles the image, but the second click does not do anything. It seems as if it is not recognizing the new class. Here is a fiddle.
https://jsfiddle.net/myfb44yu/
This is the problematic javascript.
$(document).ready(function(){
$('.first').click(function(){
alert('works');
$('#testButton').toggleClass('first', 'second');
});
$('.second').click(function(){
alert("works");
$('#testButton').toggleClass('second', 'first');
});
});
The interesting thing is that it works when I use an alert() to check but not when I try to change an img src.
Your main issue here is a syntax error in regards to your .toggleClass, but seeing as others have addressed that, I'd like to point out that you should consider re-thinking how you apply your listeners - just as good habit moving forward.
An overview of jQuery Event Bindings
Think of the elements on your page as items in a store. You're an employee, and your manager says "Go put a red tag on anything in the toys department", and so you do. The next day, he puts 10 new toys in the toy department, and says to you "Why don't all the toys have red tags on them?" He then moves one of the toys to the clothing section and asks you, "Why does this item have a red tag on it?" It's simple. You put the red tags on anything in the toys department when he told you to do it - things got moved around afterwards.
The toys in this example would be your .first and .second elements.
This is how jQuery event bindings work - they only apply to elements that satisfied the selector at the time the event was initialized.
So, if you do $('.myClass').click();, then put .myClass on five buttons - none of those buttons will call this function, as they didn't have listeners put on them.
Similarly, if you put a listener on an element using class, but then remove the class from that element, it will maintain the bound event.
The Solution
$(document).on("click", ".first", function() { } );
This is known as event delegation.
In continuing with my analogy from before, this would be the equivalent of skipping tagging the items altogether, and instead just deciding whether or not they're a toy when the customer brings them to the cash register.
Instead of putting the listener on specific elements, we've put it on the entire page. By using ".first" as the second parameter (which takes a selector), the function will only be executed if the element has class first.
Hope this helps.
EDIT: As I was typing, JHecht left a good answer that points out the same issue I outlined above.
N number of elements can have the same class name ,so that's the reason if your trying to search it as $('.classname') returns an array ,so that's the reason your code is not working.class selector
Id is unique,each element should have a single id . In your code button has two id's and for the same button your trying to toggle first and second,you need not have two separate events for first and second
instead you can write as following
check this snippet
$(document).ready(function() {
var firstElements = $('.first')
var first = firstElements[0];
var secondElements = $('.second');
var second = secondElements[0]
$("#testButton").click(function() {
alert('works');
$(this).toggleClass('first').toggleClass('second');
});
});
.first {
color: red;
}
.second {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="img/images.jpeg" alt="" id="testImage">
<div id="testDiv">
<button type="button" id='testButton' class='first'>Hi</button>
</div>
Hope it helps
Ho about this solution. Hope it helps!
$(document).ready(function(){
$("#testButton").click(function(){
if($(this).prop("class") === "first"){
alert('first');
$(this).removeClass("first").addClass("second");
}
else if($(this).prop("class") === "second"){
alert("second");
$(this).removeClass("second").addClass("first");
}
});
});
.first{
color: red;
}
.second{
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<img src="img/images.jpeg" alt="" id="testImage">
<div id="testDiv">
<button type="button" id='testButton' class='first'>Hi</button>
</div>
I hope that what I am about to say makes more sense than I feel it does.
Your issue is that when you assign the click events, there is not currently an element that has a class of .second.
Also, your code is wrong. toggleClass accepts a few arguments, the first is a string of classes, the second is an optional parameter to check whether or not to toggle the classes on or off.
A way to accomplish what you want without changing a whole lot of code is event delegation, shown below.
$(function() {
$(document).on('click', '.btn-first,.btn-second', function() {
//here we are adding the click event on the document object, and telling it that we only want to delegate this event to an object that matches the classes of .btn-first or .btn-second.
//Note: to those saying "why not just do it on the .btn class an avoid having to do this", it is so he can see what delegation looks like. But you are correct, with this markup it would be better to simply add the click event on the .btn class.
$(this).toggleClass('btn-first btn-second');
});
});
.btn {
padding: 4px 8px;
border-radius: 3px;
border: 1px solid grey;
}
.btn-first {
background-color: green;
border-color: green;
}
.btn-second {
background-color: orange;
border-color: orange
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="img/images.jpeg" alt="" id="testImage">
<div id="testDiv">
<button type="button" id='testButton' class='btn btn-first'>Hi</button>
</div>
A combination of javascript, CSS and HTML to toggle the class of #testButton when any element of class "first" or "second" is clicked, including the test button itself. The posted code was changed to supply JQuery's .toggleClass method with a space separated list of class names. Click "run snippet" to test the effect.
$(document).ready(function(){
$('.first').click(function(){
$('#testButton').toggleClass('first second');
});
$('.second').click(function(){
$('#testButton').toggleClass('first second');
});
});
.first { border: thick outset green;}
.second { border: thick inset red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="first">This paragraph has first class</p>
<p class="second">This paragraph has second class</p>
<button type="button" id="testButton" class="first">this button starts out first class</div>
The script can then be simplified by combining multiple class names in a single selector, leaving just:
$(document).ready(function(){
$('.first, .second').click(function(){
$('#testButton').toggleClass('first second');
});
});
Make a neutral class that the buttons both share (.btn).
Then add one of the state classes to each button (.first or .second).
Delegate the click event to the neutral class only ($('.btn').on('click',...).
Then toggle both state classes on this ($(this).toggleClass('first second');)
The images change by CSS, each button has 2 images which alternate between display:none/block according to the button's state class.
There is an example with the images outside of buttons and another example that doesn't toggle classes around.
SNIPPET
$('.btn').on('click', function() {
$(this).toggleClass('first second');
});
/* OR */
$('.alt').on('click', function() {
$('.img').toggle();
});
.first > .one {
display: block;
}
.first > .two {
display: none;
}
.second > .one {
display: none;
}
.second > .two {
display: block;
}
.first + .one {
display: block;
}
.first + .one + .two {
display: none;
}
.second + .one {
display: none;
}
.second + .one + .two {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Use jQuery with CSS</p>
<button class='btn first'>
<img src='http://placehold.it/50x50/000/fff?text=1' class='one'>
<img src='http://placehold.it/50x50/fff/000?text=2' class='two'>
</button>
<button class='btn second'>
<img src='http://placehold.it/50x50/0e0/960?text=1' class='one'>
<img src='http://placehold.it/50x50/fff/000?text=2' class='two'>
</button>
<br/>
<br/>
<button class='btn first'>Toggle</button>
<img src='http://placehold.it/50x50/fc0/00f?text=1' class='one'>
<img src='http://placehold.it/50x50/00f/fc0?text=2' class='two'>
<button class='btn second'>Toggle</button>
<img src='http://placehold.it/50x50/fc0/00f?text=1' class='one'>
<img src='http://placehold.it/50x50/00f/fc0?text=2' class='two'>
<p>Or use only jQuery no CSS</p>
<img src='http://placehold.it/50x50/0e0/930?text=1' class='img'>
<img src='http://placehold.it/50x50/930/0e0?text=2' class='img' style='display:none'>
<button class='alt' style='display:block;'>Toggle</button>
I'm animating images using JQuery. I'm using a button to activate the animation.
Here is my code:
$(document).ready(function(){
$("#b1").click(function(){ // b1 is the id of button
$(#img).animate({left: '+=20px'}); // img is the id of image
});
});
I have five images so when I click on another image, I need to put its id into the $(#img) instead of #img. So the second image will be animated.
How do I do this?
It sounds like you need to:
$(document).ready(function(){
// declare a variable to store the selected image
var selected = null;
// listen to clicks on all your images
// note: might want to filter this down to your target images
$("img").click(function(){
// save the selected image
selected = this
});
$("#b1").click(function(){
// animate the selected image
$(selected).animate({left: '+=20px'});
});
});
I hope that helps!
You can give the image a 'selected' class on click, then animate the selected:
$(document).ready(function() {
$(".image").click(function() {
// unselect others
$(".image").removeClass("selected");
// reselect this one
$(this).addClass("selected");
});
$("#b1").click(function() {
// animate selected
$(".image.selected").animate({left:'+=20px'});
});
});
html
<img class='image' src="image1"/>
<img class='image' src="image1"/>
<button id='b1'>click</button>
this will also allow you to style the selected image, eg:
.selected { border: 1px solid pink }
Add class (like img_to_animate) to images like
<img src='http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/sign-check-icon.png' style="width:50px;height:50px;" class="img_to_animate" />
<img src='http://icons.iconarchive.com/icons/graphicloads/100-flat/256/home-icon.png' style="width:50px;height:50px;" class="img_to_animate" />
JavaScript
$(".img_to_animate").click(function(){
$(this).animate({left: '+=20px'});
})
This version will move the animated image back to its original position when the button is pushed, if a different image is selected:
$('img').on('click', function() {
$('img').removeClass("active");
$(this).addClass("active");
});
$('input[type="submit"]').on('click', function() {
if ( $(this).attr('data-current-image') !== $('img.active').attr('data-image-id') ) {
$('img[data-image-id=' + $(this).attr('data-current-image') + ']').animate({left: '10'});
}
$(this).attr('data-current-image',$('img.active').attr('data-image-id'));
$('img[data-image-id=' + $(this).attr('data-current-image') + ']').animate({left: '+20'});
});
img { display: block; position: relative; margin-top: 10px; left: 10px; height: 50px; width: 75px; }
img.active { border-right: 3px solid #f90; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><input type=submit data-current-image=0 value=" Animate! ">
<img src='http://i.imgur.com/LCRO0jJ.jpg' data-image-id=1 class="active" />
<img src='http://i.imgur.com/LCRO0jJ.jpg' data-image-id=2 />
<img src='http://i.imgur.com/LCRO0jJ.jpg' data-image-id=3 />
<img src='http://i.imgur.com/LCRO0jJ.jpg' data-image-id=4 />
<img src='http://i.imgur.com/LCRO0jJ.jpg' data-image-id=5 />