Pass image id to JQuery by clicking on the image - javascript

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 />

Related

Only allowing one action and recording it in javascript

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.");
}
});
});

Enlarge one pic onclick

I'm making a website with images on it, and if you click on one of the images it should enlarge. I did that by using the toggleClass function in jquery
I enlarged the selected image like so:
$(".img1, .img2").on('click',function(){
$(this).toggleClass('enlarged');
});
the used class:
.enlarged{
position:absolute;
z-index:2;
width:500px;
height:600px;
top:-10%;
left:300px;
}
it's hard to explain but right now what happens is, when you click an image it enlarges. when you click another image, it enlarges too but overlaps/stays hidden behind the other image that's enlarged.
What I would like to happen is when img1 is enlarged and the user selects img2, it should "close" img1 and enlarge img2.
Thank you :)
UPDATE
it now works barely, it opens after spamclicking and once enlarged I can minimize it again. but then I can't enlarge it anymore.
Can anybody help me with this?
<script>
$(document).ready(function() {
$("#header").load("header.html .header");
$("#footer").load("footer.html .footer");
$("body").on('click', function(){
if(!$(".img1, .img2").hasClass('enlarged')){
$(".img1, .img2").on('click',function(){
$(this).addClass('enlarged');
});
}else{
$("body").on('click', '.enlarged', function(){
$(this).removeClass('enlarged');
});
}
});
});
</script>
You could do something like the following. This will remove the enlarged class. Then add it to the image that you have clicked on. (See jsfiddle here)
$(".img1, .img2").on('click', function() {
$(".img1, .img2").removeClass("enlarged");
$(this).toggleClass('enlarged');
});
See working example below:
$(".img1, .img2").on('click', function() {
$(".img1, .img2").removeClass("enlarged");
$(this).toggleClass('enlarged');
});
.enlarged {
position: absolute;
z-index: 2;
width: 500px;
height: 600px;
top: -10%;
left: 300px;
}
label {
font-weight: bold;
}
input[type=text] {
width: 20em
}
p {
margin: 1em 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="img1" src="https://placehold.it/350x150" alt="image" />
<img class="img2" src="https://placehold.it/350x150/F2F5A9" alt="image" />
Add a generic class to all clickable images, like 'gallery'
then
$(".gallery").on('click',function(){
//removes enlarged class from all images
$(".gallery.enlarged").removeClass('enlarged');
//adds enlarged class to clicked image
$(this).addClass('enlarged');
});
If you want to have only one "enlarged" class for the img you click on, I think the simpliest is to remove all "enlarged" class then add the class for the right element :
$(".img1, .img2").on('click',function(){
$(".img1, .img2").removeClass('enlarged');
$(this).addClass('enlarged');
});

Change image after click on image in javascript(Not using dropdown)

Right now i am changing the image by dropdown selection. But i want to change image by click on choice of image Like.
If the user click on green t-shirt image then set green image in <div>, If user click on yellow t-shirt then set yellow t-shirt in <div>.
But right now i am using dropdown for this procedure.
var bgArray = [
'https://d3s16h6oq3j5fb.cloudfront.net/1.13.0/img/new-city-home/bang-img/softtoys3.jpg',
'https://d2z4fd79oscvvx.cloudfront.net/0020715_be_my_valentine_chocolate_box_205.jpeg'
]
$('#imageroom').on('change', function() {
value = $(this).val() - 1;
$('#backgroundIMage').css({
'background-image': 'url(' + bgArray[value] + ')'
});
});
#backgroundIMage {
width: 400px;
height: 300px;
outline: 1px dotted gray;
margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label>Change image</label>
<select size="1" id="imageroom">
<option value="1">Image 1</option>
<option value="2">IMage 2</option>
</select>
<!-- for demo only -->
<hr>
<div id="backgroundIMage"></div>
You can handle the click event on an image. In the example below, I loop through the bgArray and dynamically display all the images in that array.
When one of the images is clicked, I show that image in the backgroundIMage element. Notice that I am using event delegation to make sure the image click works for any images that are dynamically added to the picker.
var bgArray = [
'https://d3s16h6oq3j5fb.cloudfront.net/1.13.0/img/new-city-home/bang-img/softtoys3.jpg',
'https://d2z4fd79oscvvx.cloudfront.net/0020715_be_my_valentine_chocolate_box_205.jpeg'
];
$("#picker").on("click", "img", function() {
//use event delegation to handle click event of any img tags in #picker
$('#backgroundIMage').css({
'background-image': 'url(' + this.src + ')'
});
//toggle selected
$("#picker img").removeClass("selected");
$(this).addClass("selected");
});
$(function() {
//initialize the picker on document load
bgArray.forEach(function(src) {
var img = new Image(50, 50);
img.src = src;
$("#picker").append(img);
});
//default the first one to be selected
$("#picker img").first().trigger("click");
});
#backgroundIMage {
width: 400px;
height: 300px;
outline: 1px dotted gray;
margin: 0 auto;
}
#picker img {
padding: 5px;
}
.selected {
background-color: dodgerblue;
border-radius: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Change image
<div id="picker"></div>
<hr>
<div id="backgroundIMage"></div>
Although it is king of hard to know exactly what you are trying to do, you should try to work with the click event of the image.
For a specific image :
$('#myImageId').click(function(){
$(this).css//etc..
});
For all images :
$('img').click(function(){
$(this).css//etc..
});

How to change img src link mouse hover?

HTML
<div module="product_listnormal">
<ul>
<li>
<input type="checkbox" class="{$product_compare_class} {$product_compare_display|display}">
<div id="prdImgWrapper">
<img src="{$image_medium}" alt="" class="prdImgImg"/>
</div>
.....
So i Add onmouseover in img tag
<img src="{$image_medium}" onmouseover="this.src={$image_medium} + 'aaa'" alt="" class="prdImgImg"/>
but it doesn't call {$image_medium}aaa link what's wrong?
ex) if $image_medium = 111.png
$image_medium + aaa = 111aaa.png
I use on mouse over and on mouse leave function like this
onmouseover='this.src = this.src.replace(".jpg","_2.jpg")' onmouseleave='this.src = this.src.replate("_2.jpg", ".jpg")'
this source can use every picture
You have two links image_medium and image_medium2.
Say image_medium="a.jpg" and image_medium_2="a_2.jpg";
Using pure JavaScript
1) You can add listener for the same using mouseenter and mouseleave events if you know values
var divToBeHovered=document.getElementById("prdImgWrapper");
//add listener
divToBeHovered.addEventListener("mouseenter",function(){
var imgEle=document.querySelector("#"+this.id+" img");
imgEle.src="a_2.jpg"; //image_medium_2
},false);
divToBeHovered.addEventListener("mouseleave",function(){
var imgEle=document.querySelector("#"+this.id+" img");
imgEle.src="a.jpg"; //image_medium
},false);
2)If you don't know values i.e src of image is dynamic then you can create one function and call it both on mouseenter and mouseleave event.
<a href="/product/detail.html{$param}" class="prdImg">
<img src="{$image_medium}"
onmouseenter="changeURLOfImage(this,'{$image_medium}aaa')"
onmouseleave="changeURLOfImage(this,'{$image_medium}')"
mouseralt="" class="prdImgImg"/></a>
function changeURLOfImage(imageElem,url){
imageElem.src="url"
}
3)Assign direct values to src
<img onmouseenter='this.src ={$image_medium}aaa' onmouseleave='this.src ={$image_medium}'/>
This can be done using pure CSS by using two images and changing the display on hover state.
a.prdImg > img {
display: inline-block;
}
a.prdImg > img + img {
display: none;
}
a.prdImg:hover > img {
display: none;
}
a.prdImg:hover > img + img {
display: inline-block;
}
<div module="product_listnormal">
<ul>
<li>
<input type="checkbox" class="{$product_compare_class} {$product_compare_display|display}">
<div id="prdImgWrapper">
<img src="http://media-cache-ak0.pinimg.com/736x/65/7e/a2/657ea254eb522135fbd59e0656a2e1dd.jpg" alt="" class="prdImgImg"/><img src="http://baconmockup.com/400/300" alt="" class="prdImgImg"/>
</div>
.....
By the way; wouldn't cause this.src={$image_medium} + 'aaa' the src to change from 111.png to 111.pngaaa?
While changing image src is not possible with css you can have 2 images(one hidden) and a container and on container mouse hover hide first image and show the second image.
something like this:
Html:
<div>
<span>This could be an image</span>
<span>This could be an image</span>
</div>
CSS:
div{
float:left;
width:200px;
height:200px;
}
div span{
width:100%;
height:100%;
display:none;
background-color:red;
}
div span:first-child{
display:block;
background-color:lime;
}
div:hover span:first-child{
display:none;
}
div:hover span:nth-child(2){
display:block;
}
have a look:
http://jsfiddle.net/mzvaan/fs6mc952/
html code like
<img src="sample1.png" id="newimg">
script like this
$(document).ready(function(e) {
$("#newimg").hover(function() {
$("#newimg").attr('src', 'sample2.png');
})
});

Selecting child of previous parent jQuery

Lately I've been trying my hand at animation using CSS and jQuery, it went well, however, now I want to do a bit more.
That is, once the user clicks information should show up on top of the image.
At the moment, I just have a few tags on which I perform the animations and class toggles.
My question is, I've thought about doing the following:
<div class= "singleImage">
<img src.... class="actualImage">
<p>text to put over the image</p>
</div>
This would be done per image which means that I'll have about 5 of them with different images.
However, I don't know how to go about selecting the previous element of class "actualImage".
Has anyone got any suggestions?
Thank you
Use the jQuery prev function. Example: Assume you want to select the image previous to the second image:
var foo = $(".singleImage").eq(1);
var bar = $(foo).prev().find('.actualImage');
Fiddle
Try this:
$('singleImage').children('.actualImage').prev();
I'm not sure why you are trying to select the previous element, but you could do something akin to this:
Bind a function to the click event for the element containing your image and caption.
Inside this function, toggle the caption.
Also, bind a click event handler to the body to detect clicks "off" the containing element.
HTML:
<a href="#" class="has-caption">
<img src="http://placehold.it/300x300" />
<span class="caption">This is a caption</span>
</a>
CSS:
a.has-caption { position: relative; }
a.has-caption .caption {
background: rgba(0, 0, 0, .25);
bottom: 0;
color: #fff;
display: none;
height: 20px;
left: 0;
line-height: 20px;
position: absolute;
width: 100%;
}
a.has-caption img { vertical-align: bottom }
JavaScript
$('a.has-caption').on('click', function(e) {
e.preventDefault(); e.stopPropagation();
var self = $(this)
, tmpId = 'toggle-' + Date.now();
self.addClass(tmpId);
$('span.caption', self).toggle();
$('body').one('click', function(e) {
if (!$(event.target).closest('.' + tmpId).length) {
$('span.caption', '.' + tmpId).hide();
self.removeClass(tmpId);
};
});
});
http://jsfiddle.net/83s7W/

Categories