Remove image when clicked - javascript

Basically, I'm trying to create a game where the goal is to click on images so they disappear.
I've made a function that spawns one image on a random location on the screen. Then I've also made an interval so it spawns 15 images in random locations. Now I want the images to disappear when clicked on.
My thoughts on doing this were to make a "click" function, so if the images are clicked the "img.style.height = '0px';
However, I'm not getting this or anything to work.

Use
<img onclick="this.style.visibility = 'hidden'" src="..." />
if you want to leave the space occupied by the image, otherwise:
<img onclick="this.style.display = 'none'" src="..." />
If you need to remove the image from an array of objects, you need to define a function as well.
In your code:
img.setAttribute("onclick", "this.style.visibility = 'hidden'" );
or
img.setAttribute("onclick", "this.style.display = 'none'" );

After you insert all images in document, define a click listener for all images and hide images on click. A simple example here
function hide(el) {
el.style.display = 'none';
}
var imgs = document.getElementsByTagName("img");
for(let i = 0; i < imgs.length; i ++) {
imgs[i].addEventListener('click', function(e) {
hide(e.target);
});
}
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgYxw854mGOAp8f16evj_WYw_Ph385nUVygQdxHvuD9b3ueJxT0A" id="1" alt="Mountain View 1">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT8_MiTkMX9nLJ9udtnwOQekIrQwUQ9KMZiU4fLfI7YhXCyIGZn" id="2" alt="Mountain View 2">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRgR4KM-zrVRmfdGPf5bll9vq4uLw7FSLpTmHUf9-RkYZ92Ey8Q" id="3" alt="Mountain View 3">
Your code should change like this
function SpawnW() {
var img = document.createElement("img");
img.setAttribute("style", "position:absolute;");
img.setAttribute("src", "women3.png");
document.body.appendChild(img);
img.setAttribute("onclick", "this.style.display = 'none'");
// pictureNumber++;
}
SpawnW();
Hope this helps you.

Related

JavaScript Text Replace

I'm using the code below to amend an image url (basically adding 'admin' to the start of the URL inside 'news' div. This works fine for what I'm trying to do, but it's causing some other problems, like blocking embedded Tweets and blocking some adverts from showing that are placed inside the 'news' div.
Is there a better way to achieve what I want that won't impact other code as I can't for the life of me understand why it's causing issues with other code, but removing the below fixes the issue with the tweets and ads?
function replaceText(){
var theDiv = document.getElementById("news");
var theText = theDiv .innerHTML;
theText = theText.replace(/ckfinder/g, 'admin/ckfinder');
theDiv.innerHTML = theText;
}
This is the image path I'm amending:
<img height="267" src="/ckfinder/userfiles/images/XXX/XXX.jpg" width="400" />
But need it to be:
<img height="267" src="admin/ckfinder/userfiles/images/XXX/XXX.jpg" width="400" />
You should be more specific and target the img tag and update the src attribute directly.
function replaceText() {
var images = document.querySelectorAll(".news img");
for (var i = 0; i < images.length; i++) {
var img = images[i];
img.src = img.src.replace(/ckfinder/g, 'admin/ckfinder');
}
}
window.onload = replaceText;
<div id="news">
<p>Don't want to update this ckfinder</p>
<img height="267" src="/ckfinder/userfiles/images/XXX/XXX.jpg" width="400" />
</div>

Change Image Source from Div with onmouseover

Is it possible to change the image source from the containing div? The images are dynamic and pulled from the database.
v = $"<div onmouseover=\"document.navIcon.src='/Images/White/{reader[2]}';\"
onmouseout=\"document.navIcon.src='/Images/{reader[2]}';\">
<img name=\"navIcon\" src=\"Images/{reader[2]}\"><br>{reader[1]}</div>";
That was my thoughts on how to do it but it doesn't appear to work as expected. I was able to get it to work when I put the onmouseover portion in the < img > however, I want it to change anywhere in the div, like over the reader[1] text, not just directly over the image.
Thoughts?
I just grabbed some images off google images. You can use this to refer to the current element.
<img
src='https://osu.ppy.sh/forum/images/smilies/50.gif'
onmouseover='this.src="http://4.bp.blogspot.com/-YrmTHhfMtFU/VJNbpDMHzgI/AAAAAAAAH8c/g3dJ1Q-QTrc/s1600/smile.png"'
onmouseout='this.src="https://osu.ppy.sh/forum/images/smilies/50.gif"'
/>
Edit..
This will change the image when you hover on anything with a "hoverme" class name.
(function() {
var img1 = "https://osu.ppy.sh/forum/images/smilies/50.gif";
var img2 = "http://4.bp.blogspot.com/-YrmTHhfMtFU/VJNbpDMHzgI/AAAAAAAAH8c/g3dJ1Q-QTrc/s1600/smile.png";
var myimg = document.getElementById('myimg');
myimg.src = img1;
var hoverables = document.getElementsByClassName('hoverme');
for (var i = hoverables.length; i--;) {
hoverables[i].addEventListener("mouseover", hoverMe, false);
hoverables[i].addEventListener("mouseout", unhoverMe, false);
}
function hoverMe() {
myimg.src = img2;
}
function unhoverMe() {
myimg.src = img1;
}
})();
<img class='hoverme' id='myimg' />
<p class='hoverme'>poooooooop</p>
<div class='hoverme'>This si a diiiiivvvvv</div>
The best way to accomplish that is to use CSS.
HTML
<img id="NavIcon">
CSS
#Navicon {
background-image: url(image1.jpg);
}
#NavIcon:hover {
background-image: url(image2.jpg);
}

Change image within div on image icon click

I have created a Javascript function which will allow me to change the image to another when the div is directly clicked but I am trying to get this function to work depending on which other image icon i select.
As you can see by the above image, i have a main div which contains a picture on browser load, and two further thumbnail divs which include different pictures, I want to create the function to change the main div if one of the smaller thumbnail divs are selected.
Current Javascript Function
function diffImage(img) {
if(img.src.match(/blank/)) img.src = "bognor.jpg";
else img.src = "images/bognor2.jpg";
}
Thanks in advance,
Sam
You would just use onclick event listeners on the icons and the function would change the large image to the image of the item clicked:
document.getElementById("icon1").onclick = function() {
document.getElementById("mainImage").src = this.src;
}
document.getElementById("icon2").onclick = function() {
document.getElementById("mainImage").src = this.src;
}
If you happen to have several icons you could make an icon class and apply the event listener like so:
var icons = document.getElementsByClassName("icon");
for(var i=0; i<icons.length; i++) {
icons[i].onclick = function(){
document.getElementById("main").src = this.src;
}
}
Fiddle Example for using classes
Although it's easier in that case to use jQuery and simply attach the event handler doing $('.icon').click(function(){ ... }). Of course you are not required to do so.
I recently did something similar where I had a table underneath the feature image of just smaller thumnail images.
$(".browseTable").on('click', 'td', function () {
var thumbNail = $(this).parent('tr').find('img').attr('src');
var feature = $('#featureImg img').attr('src');
$('#featureImg img').fadeOut(400, function () {
$(this).fadeIn(400)[0].src = thumbNail;
});
});
You could put the url of the big image in a custom data-attribute on the thumb element, such as <img src="thumb1.png" data-bigsrc="image1.png" />. Then you can add an event to all thumbnails like this:
var thumbs = document.querySelectorAll('.thumbnail');
var mainImage = document.querySelector('#mainImage');
for(var i=0; i<thumbs.length; ++i) {
thumbs[i].addEventListener('click', function(e) {
mainImage.src = e.target.getAttribute("data-bigsrc");
});
}
If you have high quality images and actually want to make them load when the user clicks, you could also use a radio button for each image, with the value set to the URL of the big image. Make the radio buttons invisible and put the thumbnails inside labels. Then you can just bind an event listener to all radio buttons and make them change the main image URL based on the radiobutton value.
Or if you want all the images to load in advance, you should just make tons of big-small image pairs and make the big image only visible if the small image's radiobutton is clicked, making an all-css solution.
As an alternative, this uses vanilla JavaScript, and three different ways of storing/naming the image files are covered.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div id="divMainImage">
<img id="mainImage" src="/images/image01Main.jpg" alt="Main image" />
</div>
<div id="divThumbnails">
<img class="thumb" src="/images/image01.jpg" alt="image01 thumbnail" />
<img class="thumb" src="/images/image02.jpg" alt="image02 thumbnail" />
<img class="thumb" src="/images/image03.jpg" alt="image03 thumbnail" />
</div>
<script type="text/javascript">
// Name both small and large images the same but with a prefix or suffix depicting thumbnail/main:
// image01.jpg (image01small.jpg) or image01Main.jpg (image01.jpg)
// image02.jpg (image02small.jpg) or image02Main.jpg (image02.jpg) etc.
// Or use two folders - one with main images, the other with thumbnails - both files named the same,
// then swap the folder to use when getting the image.
// Then use the displayed thumbnails' class to load originals:
var thumbnails = document.getElementsByClassName("thumb");
var mainImage = document.getElementById("mainImage");
for (index in thumbnails)
{
thumbnails[index].onclick = function () {
// Depending on the way used use on of the following:
mainImage.src = this.src.replace('.jpg', 'Main.jpg');
// Or
// mainImage.src = this.src.replace('thumb.jpg', '.jpg');
// Or
// mainImage.src = this.src.replace('/images/small/', '/images/large/');
}
}
</script>
</body>
</html>

All purpose image swap function

Ok, I am new to JavaScript so please keep that in mind when you answer. What I am looking for is a function that I can use that will enable me to click an image, then click another image and swap their positions on the page. For example I have a 3x4 table with 12 separate images, I click on 'image1' and then click 'image3' and the two swap. The only solutions I have found deal with swapping an image with a specified image, this is not what I need. Hope this makes sense.
Any suggestions and solutions are welcomed to help me learn! Thank you!
Also, I would like this to be 100% JavaScript and not jQuery.
HTML:
<table>
<tr>
<th id="pos1"> <img src="pic_01.gif" id="pic1" onclick="imageSwap()" alt="" border= height=100 width=100></img> </th>
<td id="pos2"> <img src="pic_02.gif" id="pic2" alt="" border= height=100 width=100> </img></td>
<td id="pos3"> <img src="pic_03.gif" alt="" border= height=100 width=100></img></td>
</tr>
Attempted JS:
imgArray[0] = new Image();
imgArray[0].src = 'pic_01.gif';
imgArray[1] = new Image();
imgArray[1].src = 'pic_02.gif';
imgArray[2] = new Image();
imgArray[2].src = 'pic_03.gif';
etc etc...
var a
var b
function imageSwap(){
getElementById.src = a
Not sure at all what to do for the swap itself
So I was bored and felt like being nice, so here's an example of image swapping, even though you made no attempt. Try to avoid being distracted by the cute kittens.
The part of the code that matters is the script:
var position = null,
target = null;
$("img").click(function(){
if ($(this).attr("class") == "border"){
$(this).toggleClass("border");
target = null;
position = null;
return false;
}
else{
$(this).toggleClass("border");
if (position == null){
position = $(this).attr("src");
$(this).toggleClass("position");
}
else{
target = $(this).attr("src");
$(this).attr("src", position);
$(".position").attr("src", target)
.toggleClass("position");
$(".border").toggleClass("border");
position = null;
target = null;
}
}
})
The <html> is just a set of images and the CSS just adds some margins and the border for the image you click. In short, the code checks whether the image has been selected. If it already has a selection border and you click it again, it deselects the image. If the image clicked hasn't been selected, it checks whether a position has been set. If a position has been set, it swaps the target (the image just clicked) with the image previously clicked. Otherwise, it sets the image clicked as the position (and then the next click will cause the images to swap).

How to find out if html element got fully loaded?

i need to know when a special html element containing images has been fully loaded.
The problem with this html element is that it gets replaced fully in the DOM on button click.
What can i do? (i do not want to assign a handler to each of the containing images btw.)
pretty ugly, but working
var soManyImgsInHere = 0;
var fooAttachEvent = function(whereAreTheImages_Container){
var where = whereAreTheImages_Container; //shorthand
var length = where.length;
soManyImgsInHere = length;
var imgs = where.getElementsByTagName('img');
for(var i=0;i<length;i++){
imgs[i].onload = function(){
soManyImgsInHere--;
if(soManyImgsInHere == 0){
alert('all imgs fully loaded'); // do whatever you want here :) all images are now fully loaded
}
}
};
let's assume your images are in a div with the id "fooImages"
then simply use this function right under this div like that:
<div id="fooImages">
<img src="1.jpg" />
<img src="2.jpg" />
<img src="3.jpg" />
</div>
<script>fooAttachEvent(document.getElementById('fooImages'));</script>
Hope this helps :)

Categories