basically, i have alot of image links, and i want these links to trigger a fixed overlap style but a unique image based on the image link clicked.
<img src="../Images/square 300/Drawing/angel face300.jpg" style='height: 300px; width: 300px;' onclick="imageurls(this, '../Images/A4/drawing/angel face.jpg')" />
^^one basic image link w/ onclick
<script>
function imageurls(elem, imgurl) {
var y = document.createElement("DIV").style.width = "100%";
y.class = "overlay-content"
var x = document.createElement("IMG").style.width = "100%";
x.setAttribute("src", imgurl);
x.setAttribute("width", "900");
x.setAttribute("height", "900");
x.setAttribute("alt", "_blank");
y.appendChild(x);
document.getElementById("Imagediv").appendChild(y).style.width = "100%";
}
function closeNav() {
document.getElementById("Imagediv").style.width = "0%";
}
</script>
^^ my java script, where the problem seems to be but im unsure what aspect of it is
<div id="Imagediv" class="overlay">
×
</div>
all my css styling works perfectly, and if i just use the document.get.element.... and remove the var x and y the overlay works.
variable declaration was wrong .use like this
var x = document.createElement("IMG")
var y = document.createElement("DIV")
Apply the style after the variable declaration.
remove the var x and y the overlay works.
Because the variable declaration was wrong so attributes was not append into the newly created element
function imageurls(elem, imgurl) {
var y = document.createElement("DIV")
y.style.width = "100%";
y.class = "overlay-content"
var x = document.createElement("IMG")
x.style.width = "100%";
x.setAttribute("src", imgurl);
x.setAttribute("width", "900px");
x.setAttribute("height", "900px");
x.setAttribute("alt", "_blank");
y.appendChild(x);
document.getElementById("Imagediv").appendChild(y).style.width = "100%";
console.log(document.getElementById('Imagediv').innerHTML)
}
function closeNav() {
document.getElementById("Imagediv").style.width = "0%";
}
<div id="Imagediv" class="overlay">
×
</div>
<img src="../Images/square 300/Drawing/angel face300.jpg" style='height: 300px; width: 300px;' onclick="imageurls(this, '../Images/A4/drawing/angel face.jpg')" />
Related
Apologies if I have created new thread for this, but I didn't get a solution elsewhere.
I am newbie to web designing and I was playing around with the <iframe> tag.
I used javascript to display a graphical chart from Google Sheets. Every time I click on the link which opens the chart (connected by iframe), the chart gets displayed once again below the previous chart and my HTML page gets elongated. I don't want that to happen. Instead, I would like to replace the old chart with the new chart in the same margins of previous generated charts.
<script>
function myFunction() {
var x = document.createElement("IFRAME");
x.setAttribute("src", "#Link_to_Google_sheet_chart");
x.height = "400";
x.width = "545";
x.style.margin = "100px 20px 200px 450px";
document.body.appendChild(x);
}
</script>
First of all, you're not supposed to have a link prefixed with #. Use https://link.com
Have you tried this?
x.src = "https://link.com";
If that doesn't work, maybe try this:
function myFunction() {
var x = document.createElement("IFRAME");
x.setAttribute("src", "https://link.com");
x.height = "400";
x.width = "545";
x.style.margin = "100px 20px 200px 450px";
x.id = "iframe-0";
document.body.appendChild(x);
}
function switch() {
document.getElementById('iframe-0').style.display = "none";
// create new iframe here, then append it
var y = document.createElement("IFRAME");
y.setAttribute("src", "https://link.com");
y.height = "400";
y.width = "545";
y.style.margin = "100px 20px 200px 450px";
y.id = "iframe-1";
document.body.appendChild(y);
}
You can assign a id to the iframe and replace it next time as below
function myFunction() {
var x = document.getElementById('unique-id');
if(typeof(x) !== 'undefined'){ //if iframe is appended only change src
return x.setAttribute("src", "#Link_to_Google_sheet_chart");
}
x = document.createElement("IFRAME");
x.id = 'unique-id';
x.setAttribute("src", "#Link_to_Google_sheet_chart");
x.height = "400";
x.width = "545";
x.style.margin = "100px 20px 200px 450px";
return document.body.appendChild(x);
}
I have a set of buttons that each add an image on the next click at the position of the click inside a specific div. However, I'm facing a problem that after I've clicked a button every click will add the image until I hit a different button. How can I make it so clicking the button only allows the onmousedown function to be called once?
Here is what I have:
function makeSnow() {
document.body.style.backgroundColor = "red";
document.getElementById("canvas").onmousedown = function() {
var x = event.clientX;
var y = event.clientY;
var pic = document.getElementById("snowballAppear");
pic.style.display = '';
pic.style.position = 'absolute';
pic.style.left = x - 50 + 'px';
pic.style.top = y - 50 + 'px';
document.body.style.backgroundColor = 'blue';
};
};
function makeCat() {
document.body.style.backgroundColor = "red";
document.getElementById("canvas").onmousedown = function() {
var x = event.clientX;
var y = event.clientY;
var pic = document.getElementById("catAppear");
pic.style.display = '';
pic.style.position = 'absolute';
pic.style.left = x - 50 + 'px';
pic.style.top = y - 50 + 'px';
document.body.style.backgroundColor = 'blue';
};
};
function makeDog() {
document.body.style.backgroundColor = "red";
document.getElementById("canvas").onmousedown = function() {
var x = event.clientX;
var y = event.clientY;
var pic = document.getElementById("dogAppear");
pic.style.display = '';
pic.style.position = 'absolute';
pic.style.left = x - 50 + 'px';
pic.style.top = y - 50 + 'px';
document.body.style.backgroundColor = 'blue';
};
};
<div id="container" class "container">
<div id='canvas' style="background-color: green; width: 300px; height: 300px;">
</div>
<ul>
<button onClick="makeSnow()">
<li>snow</li>
</button>
<button onClick="makeCat()">
<li>cat</li>
</button>
<button onClick="makeDog()">
<li>dog</li>
</button>
</ul>
<div class "picture">
<img alt="snowballAppear" id="snowballAppear" style="display: none; width: 100px; height: 100px;" src="http://vignette3.wikia.nocookie.net/pottermore/images/9/99/Snowball-lrg.png/revision/latest?cb=20130412122815" />
</div>
<div class "picture">
<img alt="catAppear" id="catAppear" style="display: none; width: 100px; height: 100px;" src="https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg?h=350&auto=compress&cs=tinysrgb" />
</div>
<div class "picture">
<img alt="dogAppear" id="dogAppear" style="display: none; width: 100px; height: 100px;" src="https://images.pexels.com/photos/39317/chihuahua-dog-puppy-cute-39317.jpeg?h=350&auto=compress&cs=tinysrgb" />
</div>
</div>
You need to replace the onmousedown event listener with a function that does nothing, in the original onmousedown event listener. Like this:
function makeCat() {
document.body.style.backgroundColor = "red";
document.getElementById("canvas").onmousedown = function() {
...
document.getElementById("canvas").onmousedown = () => {};
};
};
There are three ways to bind an event to an element in JavaScript, the old fashionned spaghetti style that is much hated these days, the intermediate style with property affectation that is not so bad but not really a good practice, and the trendy style that is using addEventListener.
Old fashionned spaghetti style :
function sayHello() {
console.log("hello");
}
<button onclick="sayHello()">Say hello</button>
Intermediate style with property affectation :
var btn = document.getElementById("btn");
btn.onclick = sayHello;
function sayHello() {
console.log("hello");
}
<button id="btn">Say hello</button>
Trendy style with addEventListener :
var btn = document.getElementById("btn");
btn.addEventListener("click", sayHello);
function sayHello() {
console.log("hello");
}
<button id="btn">Say hello</button>
The last two styles avoid the HTML+JS soup. This is considered a good practice that helps to produce "unobstrusive JavaScript" (Wikipedia to the rescue). That being said, the third approach is often the best option in that it makes it easy to deal with multiple listeners :
var btn = document.getElementById("btn");
btn.addEventListener("click", sayHello);
btn.addEventListener("click", sayGoodbye);
function sayHello() {
console.log("hello");
}
function sayGoodbye() {
console.log("goodbye");
}
<button id="btn">Say hello and goodbye</button>
Now to solve the "one click, one picture" problem you need to stop listening whenever the user clicks on the button. To do this you can either reset the onclick property, or use a new function called removeEventListener. One snippet for both options :
var btn = document.getElementById("btn");
btn.onclick = sayHello;
btn.addEventListener("click", sayGoodbye);
function sayHello() {
console.log("hello");
btn.onclick = null;
}
function sayGoodbye() {
console.log("goodbye");
btn.removeEventListener("click", sayGoodbye);
}
<button id="btn">Say hello and goodbye once</button>
Another possibility would be to use a global variable combined with an if statement. Not a best practice, but I believe it's worth mentionning it :
var shouldSayHello = false;
var masterBtn = document.getElementById("master-btn");
var slaveBtn = document.getElementById("slave-btn");
masterBtn.onclick = unlock;
slaveBtn.onclick = sayHello;
slaveBtn.style.color = "gray";
function unlock() {
shouldSayHello = true;
slaveBtn.style.color = "black";
}
function sayHello() {
if (shouldSayHello) {
console.log("hello");
shouldSayHello = false;
slaveBtn.style.color = "gray";
}
}
<button id="master-btn">Unlock</button>
<button id="slave-btn">Say hello once</button>
All this to finally answer the actual question. Note that you have to clone the hidden image element with the cloneNode function in order to add multiple cats to the canvas (we only need cats for the demo) :
var catBtn = document.getElementById("cat-btn");
catBtn.addEventListener("click", prepareCatLanding);
function prepareCatLanding() {
var canvas = document.getElementById("canvas");
document.body.style.backgroundColor = "red";
canvas.addEventListener("mousedown", appendCat);
};
function appendCat() {
var x = event.clientX;
var y = event.clientY;
var src = document.getElementById("catAppear");
this.removeEventListener("mousedown", appendCat);
pic = src.cloneNode();
pic.id = '';
pic.style.display = '';
pic.style.position = 'absolute';
pic.style.left = x - 50 + 'px';
pic.style.top = y - 50 + 'px';
src.parentNode.appendChild(pic);
document.body.style.backgroundColor = 'blue';
}
<div id="container" class="container">
<ul>
<li><button id="cat-btn">cat</button></li>
</ul>
<div id="canvas" style="background-color: green; width: 300px; height: 300px;">
</div>
<div class="picture">
<img alt="catAppear" id="catAppear" style="display: none; width: 100px; height: 100px;" src="https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg?h=350&auto=compress&cs=tinysrgb" />
</div>
</div>
I've fixed the HTML along the way. Indeed, <button><li></li></button> is not valid since <ul> only accepts list items, it should be the opposite, that is <li><button></button></li>. Moreover, class "container" should be class="container".
At the end of your event listener, you could reset the mousedown to something else that doesn't do anything:
function makeSnow() {
document.body.style.backgroundColor = "red";
document.getElementById("canvas").onmousedown = function() {
var x = event.clientX;
var y = event.clientY;
var pic = document.getElementById("catAppear");
pic.style.display = '';
pic.style.position = 'absolute';
pic.style.left = x - 50 + 'px';
pic.style.top = y - 50 + 'px';
document.body.style.backgroundColor = 'blue';
document.getElementById("canvas").onmousedown = function() {
//do nothing;
};
};
};
And then the same for the other functions.
You could use the return; statement in your functions to exit them.
You can return right after image is added, add an condition to your liking, I am not sure what exacly is your problem.
if (some condition) return;
But before anything:
class "container" and many more like it is not how you write classes in HTML, the correct notation is class="name"
The accepted answer suggests to redefine onmousedown event handler, which would work but requires you to write superfluous code. Here is shorter version by the way =).
document.getElementById("canvas").onmousedown = null;
It seems like a simple event listener which triggers only once is a suitable solution as well.
document.getElementById("canvas").addEventListener("mousedown", functionToExecuteOnceEventOccurs, { once: true });
Take a look at docs on MDN. Pay attention to browser compatibility table though, "once" option is not that widely supported.
Try to use:
break; or return; at the end of each function
I want to embed button on image using dom. There will be multiple images having multiple button on it which deletes image on click.
I want something like this - JSFiddle
Code I tried:
var div = document.createElement('div');
var parent = document.getElementById('images1');
var btn = document.createElement('input');
btn.type = 'button';
btn.className="multiple",
div.style.cssText = "position: relative; margin-bottom: 10px ; width: 100%;";
btn.style.cssText = " position: absolute; top: 10px; background-image: url(http://totravelistolearn.in/wp-content/themes/travel/images/cross-512.png); width: 20px; height: 20px; border: 0; background-size: 100%; background-repeat: no-repeat;";
//textbox.placeholder = 'Add details about attached Image';
//btn.value = "Remove";
btn.onclick = removeImage;
img = new Image();
img.style.display = 'block';
img.className = 'hi1';
img.style.cssText = 'height: 100px; width: 100px; position: relative;';
img.src = results[i];
div.appendChild(div);
div.appendChild(img);
div.appendChild(btn);
Function to remove image -
function removeImage(){
$$(this).prev("img").remove();
$$(this).remove();
div.parentNode.removeChild(div);
}
you need to use class instead of id, also closest() will do the job for you: DEMO
$('.myButton').click(function(){
$(this).closest('.MyImage').remove();
});
On button click, you can remove the div that contains that image and button, like this :
$('.myButton').on('click', function() {
$(this).closest('div.MyImage').remove();
});
As, I wouldn't advice using same id on multiple elements in one page, I have changed them to classes and then worked through that. I'd suggest you do the same, if your use-case allows you to.
Here is the updated Fiddle
As I Understand , written this code please check once.
function createItem() {
div = document.createElement("div");
div.setAttribute("class", "parent");
image = document.createElement("img");
image.src = "http://www.jpl.nasa.gov/spaceimages/images/mediumsize/PIA17011_ip.jpg";
image.style.width = "100%";
btn = document.createElement("button");
btn.setAttribute("class", "MyButton");
var textnode = document.createTextNode("X");
btn.appendChild(textnode);
btn.style.position = "absolute";
btn.style.left = "10px";
btn.style.left = "10px";
div.appendChild(image);
div.appendChild(btn);
div.style.width = "100px";
div.style.height = "100px";
div.style.overflow = "hidden";
div.style.marginBottom = "10px";
document.body.appendChild(div);
}
createItem();
createItem();
createItem();
parentDiv = document.getElementsByClassName("parent");
console.log(parentDiv.length);
buttonObject = document.getElementsByClassName("MyButton");
for (var i = 0; i < buttonObject.length; i++) {
buttonObject[i].id = i;
buttonObject[i].onclick = function() {
myId = this.getAttribute("id");
parentDiv[myId].remove()
}
}
I am using bootstrap3 on a site that allows users to upload images of their own. These images are later displayed in a given page. Problem is, some users upload photos that are either bigger or smaller in respect to the div that'll hold them. I wish to resize all these images using CSS (or even JavaScript if need be) in order for them to fit in the div whilst maintaining their aspect ratio. At the same time, I want them to be responsive.
Use the img-responsive class on your image.
From the Bootstrap documentation: "Images in Bootstrap 3 can be made responsive-friendly via the addition of the .img-responsive class. This applies max-width: 100%; and height: auto; to the image so that it scales nicely to the parent element."
Try this: https://jsfiddle.net/murkle/10jd0khz/1/
function openImageInLightBox(imageBase64) {
div = document.createElement("div");
div.id = "myLightboxDiv";
div.style.width = "80%";
div.style.height = "80%";
div.style.position = "fixed";
div.style.top = "10%";
div.style.left= "10%";
div.style.border = "7px solid rgba(0, 0, 0, 0.5)";
div.style.background = "#000";
div.style["background-image"] = "url('" + imageBase64 + "')";
div.style["background-size"] = "contain";
div.style["background-repeat"] = "no-repeat";
div.style["background-position"] = "center";
div.onclick = function() {document.body.removeChild(div);};
document.body.appendChild(div);
// now add transparent image over it
// so that "Save image as..." works
// remove this if you don't need it
var elem = document.createElement("img");
elem.src = imageBase64;
elem.style.height = "100%";
elem.style.width = "100%";
elem.style.opacity = 0;
div.appendChild(elem);
}
I have a simple game where image moves randomly and score increases when user clicks on it.
The first image displays before game is started, which when clicked calls the play() function in javascript, which hides that image and displays the image that is to be used for the game.
That is where my code is stuck, it does not call the function play(). I am new to javascript and html. Any help would be great!
Here is my code
<html>
<head>
<title>Image click Game!</title>
<script>
global var score = 0;
global var left=400;
global var top = 100;
function play() {
var game = document.getElementById('game');
var firstDiv = document.getElementById('firstDiv');
var height = window.innerHeight;
var width = window.innerWidth;
firstDiv.style = 'display : none';
game.style='display : block';
setInterval("move()", 1000);
}
function move() {
var randomNumberX = Math.floor(Math.random()*11)-5;
var randomNumberY = Math.floor(Math.random()*11)-5;
left = left + randomNumberX;
top = top+randomNumberY;
var im = document.getElementById('image');
im.style.left = left;
im.style.top = top;
}
</script>
</head>
<body>
<div id ="firstDiv" style="display : block">
<img src="pics/playgame.gif" width="108" height="106" onClick = "play()"/></a>
</div>
<div id="game" style="display : none">
<p>"Score: " + score</p>
<img id="image" src="pics/gameImage.gif" onClick = "score++" style="position:absolute; left: 400; top: 100;"/></a>
</div>
</body>
</html>
There are a handful of things wrong with your code:
1) Your <img> tags are ended with a stray, unneeded </a> tag.
2) In your <img> tag, you should change to onClick = "play();"
3) I don't believe javascript supports the global keyword in that way.
4) To change CSS style, try this:
firstDiv.style.display = 'none';
game.style.display = 'block';
5) You cannot display javascript variables in this fashion: <p>"Score: " + score</p>...not to mention there is no declared variable 'score' to begin with!
Keep working at it, you only get better with practice.
Tyr this
<script>
var score = 0;
var left=400;
var top = 100;
function play() {
var game = document.getElementById('game');
var firstDiv = document.getElementById('firstDiv');
var height = window.innerHeight;
var width = window.innerWidth;
firstDiv.style.display='none';
game.style.display='block';
setInterval("move()", 1000);
}
function move() {
var randomNumberX=Math.floor(Math.random()*11)-5;
var randomNumberY=Math.floor(Math.random()*11)-5;
left= left+randomNumberX;
top = top+randomNumberY;
var im= document.getElementById('image');
im.style.left=left;
im.style.top=top;
}