Javascript: Target image Id to display message - javascript

I've attached an onclick event on two images. I would like to display a different message for each image. How do I create an if/else statement to display one message "You Liked this Cat!" if one image is clicked and the other "You Didn't Like this Cat!"
<img src="black_cat.jpg" alt="Profile Pic" height="300" width="300" id="profile_pic"></img>
<img src="white_cat.jpg" alt="Profile Pic" height="300" width="300" id="next_profile"></img>
<img src="" alt="Swipe Left" height="150" width="150" id="swipe_left" onclick="hide_profile(); show_profile();"></img>
<img src="" alt="Swipe Right" height="150" width="150" id="swipe_right" onclick="hide_profile(); show_profile();"></img>
<p id="display_message"></p>
function hide_profile() {
document.getElementById("profile_pic").style.visibility = "hidden";
}
function show_profile() {
document.getElementById("next_profile").style.display = "block";
document.getElementById("next_profile").style.visibility = "visible";
document.getElementById("profile_pic").style.display = "none";
document.getElementById("display_message").innerHTML = "You Liked this Cat!";
}

In the HTML element you can pass its ID
<img onclick="functionName(this.id)">
And in Javascript:
function functionName(clicked_id){
if(clicked_id == "cat"){
...
}
}

You may need to add some attribute (e.g. id or rel) to your image tags and assign some unique value to them so you can identify it onclick event handler and show message accordingly.
Or rather pass some param with onclick function.
I am providing code pressuming used with jQuery.
<IMG SRC='IMG1.jpg' id='1' onclick='updatepic(1)'>
Javascript function
function updatepic(id) {
if(id==1) {
//change the innerhtml for pic 1
}
else {
//change the innerhtml for pic 2
}
}

Pass the text to the show_profile function.
Try this code:
function hide_profile() {
document.getElementById("profile_pic").style.visibility = "hidden";
}
function show_profile(message) {
document.getElementById("next_profile").style.display = "block";
document.getElementById("next_profile").style.visibility = "visible";
document.getElementById("profile_pic").style.display = "none";
document.getElementById("display_message").innerHTML = message;
}
<img src="black_cat.jpg" alt="Profile Pic" height="300" width="300" id="profile_pic"></img>
<img src="white_cat.jpg" alt="Profile Pic" height="300" width="300" id="next_profile"></img>
<img src="" alt="Swipe Left" height="150" width="150" id="swipe_left" onclick="hide_profile(); show_profile('You Liked this Cat!');"></img>
<img src="" alt="Swipe Right" height="150" width="150" id="swipe_right" onclick="hide_profile(); show_profile('You Didn\'t Like this Cat!');"></img>
<p id="display_message"></p>

Related

Any Shorter way for jquer .eq selector?

startSliding($("div").eq(0));
startSliding($("div").eq(1));
startSliding($("div").eq(2));
I would like to know if there is a different way to add only one code instead of repeating eq selector every time.
startSliding($("div").eq(unlimited));
The full js file is:
startSliding($("div").eq(0));
startSliding($("div").eq(1));
startSliding($("div").eq(2));
startSliding($("div").eq(3));
function startSliding (div) {
var i = 0;
var tid = null;
var sec = 1/3; // <- you want 1 here
var images = $("img", div).map(function () {
return $(this).attr("src");
}).get();
$("img:gt(0)", div).remove();
$("img", div).hover(function () {
var $this = $(this);
tid = setInterval(function () {
i = (i + 1) % images.length;
$this.attr("src", images[i]);
}, 1000 * sec);
}, function () {
clearInterval(tid);
$(this).attr("src", images[0]);
});
}
I got this way in another question from some one who helped me to much but now working on Im getting more ideas on my project, and the DIVs that I have in page are changing, sometimes in a page I have 10 divs sometimes 50.Adding eq selector for each div will effect in pagespeed too. so if there is a shorter code which does the same job would be great to know.I'm a newbea with javascript :(
https://jsfiddle.net/jhudrp8v/11/
Thank You!
It's very simple to do so.
You have to just use .each() jquery method.
Check below code snippet for the same -
// Added code
let elem = $('div.someclass');
elem.each(function(i) {
startSliding(elem.eq(i));
});
// Your code
function startSliding (div) {
var i = 0;
var tid = null;
var sec = 1/3; // <- you want 1 here
var images = $("img", div).map(function () {
return $(this).attr("src");
}).get();
$("img:gt(0)", div).remove();
$("img", div).hover(function () {
var $this = $(this);
tid = setInterval(function () {
i = (i + 1) % images.length;
$this.attr("src", images[i]);
}, 1000 * sec);
}, function () {
clearInterval(tid);
$(this).attr("src", images[0]);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="someclass">
<img height="150" src="https://i.stack.imgur.com/BDcMh.gif">
<img height="150" src="https://i.stack.imgur.com/vfQCT.gif">
<img height="150" src="https://i.stack.imgur.com/MbEgw.gif">
<img height="150" src="https://i.stack.imgur.com/uCCEw.gif">
<img height="150" src="https://i.stack.imgur.com/iO6QE.gif">
</div>
<div class="someclass">
<img height="150" src="https://i.stack.imgur.com/BDcMh.gif">
<img height="150" src="https://i.stack.imgur.com/vfQCT.gif">
<img height="150" src="https://i.stack.imgur.com/MbEgw.gif">
<img height="150" src="https://i.stack.imgur.com/uCCEw.gif">
<img height="150" src="https://i.stack.imgur.com/iO6QE.gif">
</div>
<div class="someclass">
<img height="150" src="https://i.stack.imgur.com/BDcMh.gif">
<img height="150" src="https://i.stack.imgur.com/vfQCT.gif">
<img height="150" src="https://i.stack.imgur.com/MbEgw.gif">
<img height="150" src="https://i.stack.imgur.com/uCCEw.gif">
<img height="150" src="https://i.stack.imgur.com/iO6QE.gif">
</div>
<div class="someclass">
<img height="150" src="https://i.stack.imgur.com/BDcMh.gif">
<img height="150" src="https://i.stack.imgur.com/vfQCT.gif">
<img height="150" src="https://i.stack.imgur.com/MbEgw.gif">
<img height="150" src="https://i.stack.imgur.com/uCCEw.gif">
<img height="150" src="https://i.stack.imgur.com/iO6QE.gif">
</div>
For more info on .each() refer https://api.jquery.com/eq/
Hope this will help you :)

onclick get index of image in for loop javascript

onclick get image index in for loop in javascript not jquery, the main problem here is that i can't access any global variable in function
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<title></title>
</head>
<body>
<img src="images/2.jpg" width="350" height="250">
<img src="images/3.jpg" width="350" height="250">
<img src="images/4.jpg" width="350" height="250">
<img src="images/5.jpg" width="350" height="250">
<img src="images/6.jpg" width="350" height="250">
<img src="images/7.jpg" width="350" height="250">
<script type="text/javascript" src="scripts/script.js"></script>
</body>
</html>
/*external javascript file code */
var img = document.images;
var i;
for(i=0;i<img.length;i++){
img[i].src = "images/1.jpg";
//after changing image src i just want to show index of clicked image
img[i].onclick = function(){
alert("i m img "+ i);
console.log(i);
}
console.log(i);
}
You can store the index in your own html attribute like index-data using setAttribute and getAttribute:
var img = document.images;
var i;
for (i = 0; i < img.length; i++) {
img[i].src = "images/1.jpg";
img[i].setAttribute("index-data", i);
//after changing image src i just want to show index of clicked image
img[i].onclick = function() {
var index = this.getAttribute("index-data");
console.log(index);
}
}
<img src="images/2.jpg" width="350" height="250">
<img src="images/3.jpg" width="350" height="250">
<img src="images/4.jpg" width="350" height="250">
<img src="images/5.jpg" width="350" height="250">
<img src="images/6.jpg" width="350" height="250">
<img src="images/7.jpg" width="350" height="250">
You can use the attribute dataset to store the current index.
var img = document.images;
var i;
var images = ['https://www.hrexaminer.com/wp-content/uploads/2016/10/2016-10-11-hrexaminer-stackoverflow-6-xxl-sq-250px.png', 'https://i.stack.imgur.com/G2FO1.jpg?s=48&g=1']
for (i = 0; i < img.length; i++) {
img[i].src = images[i];
img[i].dataset.index = i;
img[i].onclick = function() {
var index = this.dataset.index;
console.log(index);
}
}
<img src="" width="100" height="100">
<img src="" width="100" height="100">
This is a classical closure problem inside a loop.
The simple solution to this problem is to wrap the code block which has
indefinite execution, inside a IIFE block.
read about it here : Javascript closures
for(i=0;i<img.length;i++){
img[i].src = "images/1.jpg";
(function(index){
img[index].onclick = function(){
alert("i m img "+ index);
console.log(index);
}
})(i)
}

How to add percentages in Javascript

I'm trying to make a slider by adding 100% to each image but can not get it done.
My main question is how to add the percentages. I tried console.log(100% + 100%) just for an example and it does not work either. Thanks for any suggestions.
<section class="slider">
<img class="img" id="img1" src="girl.jpg" alt="" style="left: -100%">
<img class="img" id="img2" src="sport.jpg" alt="" style="left: 200%" >
<img class="img" id="img3" src="biceps.jpg" alt="" style="left: 100%" >
<img class="img" id="img4" src="weights.jpg" alt="" style="left: 0%">
</section>
javascript
var img = document.getElementsByClassName('img');
function slide() {
for(i=0; i < img.length; i++) {
img[i].style.left += "100%";
console.log(img[i].style.left);
}
}
You can't because this attribute's value is not a number (it's a text). So here's what you can do:
Try to parse the text to get only the number portion, parse it into an integer, do the math, then turn it back to a string. Something like
let tempPercent = parseInt(img[i].style.left.replace('%', ''), 10);
tempPercent += 100;
img[i].style.left = tempPercent+'%';

Javascript code for remove image

I want to make this Javascript code to when I click "remove image" link , it remove the image. Please help me.
<script>
function previewFile(){
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
previewFile();
</script>
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
remove image
</body>
</html>
<img id='image' src="" height="200" alt="Image preview...">
<a id='remove' href="#">remove image </a>
<script>
$(function rmv() {
$('#remove').click(function() {
$('#image').remove();
}
});
</script>
If you cannot add id attribute to that img, you can remove it like this with raw javascript - it assumes the image is preceding the anchor tag directly, allowing for only one text node between them:
function removeImage(el){
if(!el.previousSibling.tagName){//if it is textnode like newline etc. we go one back
var el = el.previousSibling;
}
if(el.previousSibling.tagName && el.previousSibling.tagName=='IMG'){
el.previousSibling.remove();
}
}
<img src="" height="200" alt="Image preview...">
remove image
Keep img element in div and assign id to both this element
<input type="file" onchange="previewFile()"><br>
<div id="imgDiv"> <img id="image1" src="" height="200" alt="Image preview..."></div>
remove image
</body>
</html>
<script>
function previewFile() {
var d = document.getElementById('imgDiv');
var olddiv = document.getElementById("image1");
d.removeChild(olddiv);
}
</script>
<img src="" id="image" height="200" alt="Image preview...">
remove image
JS:
function foo(){
var image = document.getElementById("image");
if (image != null)
{
image.parentNode.removeChild(image);
}
}

Clicking on thumbnail changes an unintended main image

When I click on a thumbnail meant to change (img), it changes the main image of (img1) as well.
I would want only AGM thumbnails to change (img), and BLACSBF to change (img1)
Would appreciate any assistance. (:
My Javascript
function changeImage(img) {
document.getElementById("img").src = img.src.replace("_t", "_b");
document.getElementById("img1").src = img.src.replace("_t", "_b");
My HTML
<img src="images/AGM/events_t.jpg"
onclick='changeImage(this);'
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img src="images/AGM/events1_t.jpg"
onclick='changeImage(this);'
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img id="img" src="images/AGM/events_b.jpg" width="650">
<img src="images/BLACSBF/events_t.jpg"
onclick='changeImage(this);'
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img src="images/BLACSBF/events1_t.jpg"
onclick='changeImage(this);'
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img id="img1" src="images/BLACSBF/events_b.jpg" width="650">
Thank you very much!
You need to pass the targeted image element as a parameter to the changeImage function
function changeImage(img, target) {
document.getElementById(target).src = img.src.replace("_t", "_b");
}
then
<img src="images/AGM/events_t.jpg"
onclick="changeImage(this, 'img');"
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img src="images/AGM/events1_t.jpg"
onclick="changeImage(this, 'img');"
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img id="img" src="images/AGM/events_b.jpg" width="650">
<img src="images/BLACSBF/events_t.jpg"
onclick="changeImage(this, 'img1');"
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img src="images/BLACSBF/events1_t.jpg"
onclick="changeImage(this, 'img1');"
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img id="img1" src="images/BLACSBF/events_b.jpg" width="650">
You might be able to simplify your markup a little more if you attached event handlers directly in JavaScript. This isn't a cross browser method, but it certainly does work. Firstly you could slim down your markup and turn the bigger img elements into classes, instead of having a bunch of unique IDs to worry about:
<img src="images/AGM/events_t.jpg">
<img src="images/AGM/events1_t.jpg">
<img class="img" src="images/AGM/events_b.jpg" width="650">
<img src="images/BLACSBF/events_t.jpg">
<img src="images/BLACSBF/events1_t.jpg">
<img class="img" src="images/BLACSBF/events_b.jpg" width="650">
Then, in your JavaScript, you could cycle through all the img tags that don't have a class attribute, and add your event handlers with addEventListener() ( this is the part that will not work on IE8, but can be easily fixed with a cross browser implementation).
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
if (!imgs[i].getAttribute('class')) {
//mouseout handler
imgs[i].addEventListener("mouseout", function () {
this.style.opacity = 1;
this.filters.alpha.opacity = 100;
});
//mouseover handler
imgs[i].addEventListener("mouseover", function () {
this.style.opacity = 0.5;
this.filters.alpha.opacity = 0.5;
});
//click handler
imgs[i].addEventListener("click", function () {
var src = this.src.replace("_t", "_b");
var fullImg = siblingByClass(this);
fullImg.src = src;
//traverse siblings till 'img' class is found
function siblingByClass(node) {
var sibling = node.nextSibling;
if (sibling.nodeType === 3 || sibling.getAttribute('class') !== 'img') {
return siblingByClass(sibling);
} else {
return sibling;
}
}
});
}
}
jsFiddle

Categories