I am building a application where user can write something inside input and it will be converted to a image they can download.
I use html2canvas.js for converting text to a downloadable image (this part works fine)
Currently it take the text inside <div id="talltweets"></div> and converts it to a image, but what I want is to be able to change the text/image when writing text inside input.
I tried to make a function called edValueKeyPress and it takes whats inside the input and adds it into <div id="talltweets"></div>, Now how can I take the text inside #talltweets and add it to <img id="textScreenshot"/> in realtime/when writing?
This is my code:
html2canvas(document.getElementById("talltweets"), {
onrendered: function(canvas) {
var screenshot = canvas.toDataURL("image/png");
document.getElementById("textScreenshot").setAttribute("src", screenshot);
}
});
function edValueKeyPress() {
var edValue = document.getElementById("body");
var s = edValue.value;
var lblValue = document.getElementById("talltweets");
lblValue.innerText = s;
}
<script src="http://files.codepedia.info/uploads/iScripts/html2canvas.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<input type="text" onKeyPress="edValueKeyPress()" onKeyUp="edValueKeyPress()" id="body">
<div id="talltweets"></div>
<!-- The PNG image will be added here-->
<div>
<img id="textScreenshot" />
</div>
Basically, you need to wrap that whole rendering step of the process into a function that can then be called with the keypress event. You're already on the right track - here's one way you could implement this (plus a few miscellaneous code improvements; also, I had to change the URL for html2canvas to pull from a different cdn, as the original one wasn't loading correctly from SO):
// If we store these, we only need to query the dom once, not on every update
var tallTweets = document.getElementById('talltweets');
var screenshotImg = document.getElementById('textScreenshot');
var textInput = document.getElementById('body');
// Note - it wouldn't surprise me if html2canvas has a specific API
// for doing this kind of update. Worth checking their documentation for.
function updateImage() {
html2canvas(tallTweets, {
onrendered: function(canvas) {
var screenshot = canvas.toDataURL("image/png");
screenshotImg.setAttribute("src", screenshot);
}
});
};
function edValueKeyPress() {
tallTweets.innerText = textInput.value || '';
updateImage();
}
updateImage();
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<input type="text" onKeyPress="edValueKeyPress()" onKeyUp="edValueKeyPress()" id="body" placeholder="Type something!">
<div id="talltweets"></div>
<!-- The PNG image will be added here-->
<div>
<img id="textScreenshot" alt="Generated screenshot" />
</div>
You could also make it even simpler by combining the two functions into one - IE, moving tallTweets.innerText = textInput.value into updateImage, and then binding the event listener to updateImage instead. But keeping them separated has its advantages, especially if you might want to reuse updateImage elsewhere.
Related
I'm creating an accordion with my own arrow icons (pngs) as the "toggle" so when you click on the down red arrow, the up blue arrow will show to collapse, and vice versa.
I got it to work with the below code, but I have multiple accordions with the same arrow icons, and I need them all to do this. When I add the same code to the other accordions (even if I changed out the ID to be unique and update it in the JS), it still only wants to toggle the first accordion.
Can anyone help me get this to work across multiple image sets (but the same images)?
HTML:
<img src="/wp-content/uploads/2019/08/accordion-open.png" alt="accordion icon" id="accordion" onclick="change();"></div>
JS:
var image_tracker = 'open';
function change(){
var image = document.getElementById('accordion');
if(image_tracker=='open'){
image.src='/wp-content/uploads/2019/08/accordion-close.png';
image_tracker='close';
}
else{
image.src='/wp-content/uploads/2019/08/accordion-open.png';
image_tracker='open';
}
}
If you're assigning the listener by ID it's only going to apply to the first one. Try using a class name instead.
<html>
<body>
<img class="accordion_icon" src="/wp-content/uploads/2019/08/accordion-open.png" />
<script type="text/javascript">
var open_src = "/wp-content/uploads/2019/08/accordion-open.png";
var close_src = "/wp-content/uploads/2019/08/accordion-close.png";
let accordion_icons = document.getElementsByClassName('accordion_icon'); // get all icons img tags
for (let i = 0; i < accordion_icons.length; i++) {
const element = accordion_icons[i];
element.addEventListener('click',(event)=>{ // set listener on each one
console.log('src was: ', event.currentTarget.src);
event.currentTarget.src = (event.currentTarget.src == open_src ? close_src : open_src) // change the src to the one it currently isn't
console.log('scr is now: ', event.currentTarget.src);
});
}
</script>
</body>
</html>
An alternative method could be also this one, if you still want to keep the even handler in the HTML:
<img src="/wp-content/uploads/2019/08/accordion-open.png" alt="accordion icon" id="accordion" onclick="change(this);"></div>
And in the JS:
function change(image){
image.src = image.src.endsWith("open.png")
? image.src.replace(/open\.png$/, "close.png")
: image.src.replace(/close\.png$/, "open.png");
}
So I am very new to Web Design and am having issues getting my click event handler to work.I cant change the html or css files. My task is to set a click handler to my thumbnails to enlarge the image in the img within the <figure> element. While also setting the figcaption text in the figure to the thumbs title attribute. I need to attach to the div id = thumbnails. My script is not enlarging my thumbnails or titles.
This is my created HTML Doc:
<!DOCTYPE html>
<html lang="en">
<head >
<meta charset="utf-8">
<title>Chapter 9 - Share Your Travels</title>
<link rel="stylesheet" href="css/styles.css" />
<script type="text/javascript" src="js/chapter09-project02.js">
</script>
` `</head>
<body>
<header>
<h2>Share Your Travels</h2>
<nav><img src="images/menu.png"></nav>
</header>
<main>
<figure id="featured">
<img src="images/medium/5855774224.jpg" title="Battle" />
<figcaption>Battle</figcaption>
</figure>
<div id="thumbnails">
<img src="images/small/5855774224.jpg" title="Battle"/>
<img src="images/small/5856697109.jpg" title="Luneburg"/>
<img src="images/small/6119130918.jpg" title="Bermuda" />
<img src="images/small/8711645510.jpg" title="Athens" />
<img src="images/small/9504449928.jpg" title="Florence" />
</div>
</main>
</body>
</html>
Js script:
var thumbs = document.getElementById("thumbnails");
thumbs.addEventListener("click", function (e) {
if (e.target.nodeName.toLowerCase() == 'img') {
var clickedImageSource = e.target.src;
var newSrc = clickedImageSource.replace("small", "medium");
var featuredImage = document.querySelector("#featured img");
featuredImage.src = newSrc;
featuredImage.title = e.target.title;
}
});
var img = document.getElementById("figcaption");
img.addEventListener("mouseover",function (event) {
img.className = "featured figcaption";
});
img.addEventListener("mouseout", function (event) {
img.className = "featured figcaption";
var element = document.getElementById('figcaption');
element.style.opacity = "0.9";
element.style.filter = 'alpha(opacity=0%)';
});
Thanks for any advice and hopefully I can pay it forward for someone else!
I think it causes you the problem. The JS is getElementById, but there's no ID is call figcaption.
var img = document.getElementById("figcaption");
The problem is that you are trying to use getElementById to find something with the id of figcaption; nothing on the page has an id of figcaption, so getElementById returns null.
There are a few ways you could fix it:
Add an id to your <figcaption> element: <figcaption id="figcaption">
Instead of using getElementById, use getElementsByTagName: document.getElementsByTagName('figcaption')[0];. (getElementsByTagName always returns a collection of elements, the [0] grabs the first, and in this case only, one in the collection).
Instead of using getElementById, use querySelector like you did to find the featured image element: document.querySelector("#featured figcaption");
This last approach of using querySelector is what I would recommend in this situation; other times it might be better to add an id to the element.
const thumbs = document.getElementById("thumbnails");
const featuredImage = document.querySelector("#featured img");
const caption = document.querySelector("#featured figcaption");
thumbs.addEventListener("click", function (e) {
if (e.target.nodeName.toLowerCase() == 'img') {
var clickedImageSource = e.target.src;
// for the purposes of this demo, I'm using a placeholder
// image service so I need to change the size slightly differently
let newSrc = clickedImageSource.replace("50x50", "350x150");
//var newSrc = clickedImageSource.replace("small", "medium");
featuredImage.src = newSrc;
caption.textContent = e.target.title;
}
});
caption.addEventListener("mouseover",function (event) {
caption.className = "featured figcaption";
});
caption.addEventListener("mouseout", function (event) {
caption.className = "featured figcaption";
// I changed the value to .5 instead of .9 because with such small
// text the opacity change is barely perceivable.
caption.style.opacity = "0.5";
// This is not needed, this was the old way IE used to do it,
// IE < 9 needed it, but IE < 9 is no longer relevant. Just use opacity.
//element.style.filter = 'alpha(opacity=0%)';
});
<header>
<h2>Share Your Travels</h2>
<nav><img src="http://via.placeholder.com/50x50?text=Menu"></nav>
</header>
<main>
<figure id="featured">
<img src="http://via.placeholder.com/350x150" title="Battle">
<figcaption>Battle</figcaption>
</figure>
<div id="thumbnails">
<img src="http://via.placeholder.com/50x50" title="Battle">
<img src="http://via.placeholder.com/50x50/ff0000/ffffff" title="Luneburg">
<img src="http://via.placeholder.com/50x50/00ff00/ffffff" title="Bermuda">
<img src="http://via.placeholder.com/50x50/0000ff/ffffff" title="Athens">
<img src="http://via.placeholder.com/50x50/000000/ffffff" title="Florence">
</div>
</main>
A few things to note about my version, I used let and const instead of var. Both let and const are well supported these days and should be used instead of var unless you need to support very old browsers. I also only query for the caption and featured image elements once and store them in the scope above the click handler, this allows the code inside the click handler to have access to them via closure. This makes everything slightly more efficient since you don't have to query the DOM to find them each time the click handler runs. In this case the performance gain is moot but it is good to be in the habit of writing code as efficiently as possible so you don't have to think about it when it does matter.
Images are void elements, meaning they can't have any content, so you don't need a closing tag. For this reason I used bare <img> tags instead of self-closing <img /> tags. Self-closing images were only ever needed in XHTML, since it was XML, which has a more rigid syntax than HTML. Another thing to note, you don't need the type="text/javascript" on your <script> tags, it just takes up extra space and doesn't really do anything.
I don't understand what you are trying to do with the mouseover and mouseout handlers. Currently what your code does is:
When the mouse moves over the caption, the featured and figcaption classes are added to the caption.
When the mouse leaves the caption, the featured and figcaption classes are again added to the caption and its opacity is set to 0.9, effectively permanently.
I cleaned it up a little in my example to make it more obvious that is what is happening.
I know there are other questions like this and I've tried following them I'm just not aware of what exactly I'm doing wrong. I've declared the pic variable as being linked to the image with the corresponding id of 'pic' and I've tried many different examples and trying to follow other questions like this but to no avail.
--- THE REAL QUESTION ----
I would like the image to change its src to another one that I have in my workspace with the click of a button.
HTML:
<img class="trans" id="pic" src="images/link_rouge.png" alt="" width="1000" height="333" />
JavaScript:
var pic = document.getElementById('pic');
function rouge() {
pic.src = "images/link_rouge.png";
}
function blue() {
pic.src = "images/link_blue.png";
}
I know the functions already work with the buttons because they are affecting some divs on the page that change color the only things not changing are the images.
The EventTarget.addEventListener() method registers the specified listener on the EventTarget it's called on.
Use addEventListener over button elements to attach click events and bind your handler functions to those events.
var pic = document.getElementById('pic');
function rouge() {
pic.src = "http://www.projectvictorycosplay.com/images/zelda/Links/3198_render_link.png";
}
function blue() {
pic.src = "http://bin.smwcentral.net/u/1944/Link%2BBlue%2BTP%2Bshrunk.png";
}
document.getElementById('btn1').addEventListener('click', rouge);
document.getElementById('btn2').addEventListener('click', blue);
img {
width: 200px;
}
<button id='btn1'>rouge</button>
<button id='btn2'>blue</button>
<br/>
<img class="trans" id="pic" src="http://www.projectvictorycosplay.com/images/zelda/Links/3198_render_link.png" alt="" width="1000" height="333" />
There's a chance your page has not loaded before pic is set equal to document.getElementById('pic');.
You can use something like jQuery's $(document).ready() function (or document.addEventListener("DOMContentLoaded", handler);) to ensure your page is fully loaded before assigning the pic variable.
$( document ).ready(function() {
var pic = document.getElementById('pic');
function rouge() {
pic.src = "images/link_rouge.png";
}
function blue() {
pic.src = "images/link_blue.png";
}
});
Note: You will need to pull the JQuery library into your project to use this method. See here.
Also, you can read this post to learn a little more about HTML/JavaScript and page loading.
I know this question is a bit lengthy, but all of it is related so I am putting them here.I am trying this since past 2 days and i am very close of getting a solution.But something is wrong in css or scripting code can't understand where.
Following is the fiddle link I received as a response to my question click here to view
You can view my question here .
In order to test it I simply copied and pasted the code as given in the link and saved as demo.html. The contents are exactly this:
<body>
<header>
<h1>File API - FileReader (Text)</h1>
</header>
<article>
<label for="files">Select a file: </label>
<input id="files" type="file" onchange="readURL(this);" /><br>
div<div id="result"></div><br>
img<img src='' id="img"><br>
</article>
<script>
var readURL;
window.onload = function() {
//Check File API support
readURL = function(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = (function (tFile) {
return function (evt) {
//$('#img').attr('src', evt.target.result);
$('#result').css({'background-image': 'url('+evt.target.result+')','background-size': '200px 200px', 'background-repeat': 'no-repeat', 'background-position':'center'})
};
}(input.files[0]));
reader.readAsDataURL(input.files[0]);
}
}
}
</script>
</body>
Problem-1 is that image is not showing up.I simply can't understand why?
Problem-2:
Next with code posted in my previous question you can view here. I am at least able to set the background. But not resize the background image even if I use background-size after background or irrespective of the property-value pair in quotes or not.I have accepted the answer because fiddle was working,but problem is still unresolved. Is it that .css() function of jQuery is not taking multiple values well in that case this fiddle
must also not work. But its working.
Problem-3:
Another point of interest is switching the background image on-click multiple times like for eg. onclick of button for red background changes to red but onclick of upload image is uploaded and background becomes image. Now I have implemented both in single page.I can show you the code on request.Problem is once I set image as background I cannot simply change it back to color. Note the script of color change in the background is before image change script.
You can choose to answer any of the problem according to your expertise. Any help or links or research will be appreciated.
You need this style for it to work:
#result {
height: 300px;
width: 100%;
}
You also need to add query:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
For your first problem..
I didn't dig why exactly your fiddle had an error of 'readURL' is undefined
but since you used jquery, I attached the event and called it with jquery
and now it works:
$(function () {
$("#files").on('change', readURL);
});
//Check File API support
function readURL() {
var input = this;
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = (function (tFile) {
return function (evt) {
//$('#img').attr('src', evt.target.result);
$('#result').css({ 'background-image': 'url(' + evt.target.result + ')', 'background-size': '200px 200px', 'background-repeat': 'no-repeat', 'background-position': 'center' })
};
}(input.files[0]));
reader.readAsDataURL(input.files[0]);
}
}
working demo
I wrote this function to change my pic what is the problem?
my aim is when clicking on a pic toggle between 2 images if image p is showing by clicking shows me image p1
I have this in script:
<script>
function changeimage()
{
if(this.getElementById('myimage').src=="../../images/p1.gif")
{
document.getElementById('myimage').src="../../images/p.gif";
}
else
{
document.getElementById('myimage').src="../../images/p1.gif";
}
}
</script>
in the html part I have these ones which are more than one picture but I set the whole of them with Id=myimage is it wrong to set the whole one same ID?:
<table width="100%">
<tr>
<td><img id='myimage' src="../../images/p1.gif" onclick="changeimage();setTable('table2');setTable('table2-2');check('table3');check('table3-3');check('table3-3-3');check('table4');check('table5');check('table6');check('table6-1');"></td>
<td style="font-weight: bold;font-size:13; font-family:arial,verdana;" width="25%">General Rule Options</td>
<td valign="bottom" width="100%">
I have many rows in my tables like this
The problem is the following line:
if(this.getElementById('myimage').src=="../../images/p1.gif")
In particular, it's the use of this. In your function this will refer to the window, and the window doesn't have a getElementById method. Use document like you have in the other cases:
if(document.getElementById('myimage').src=="../../images/p1.gif") {
//...
}
And it looks like it should work fine. Alternatively, you can pass in an a reference to the clicked element when you call the event handler, and reference that instead of using getElementById. For example:
onclick="changeimage(this);"
You call changeImage() from the <img> element, and then reference this inside the function. Since the function runs without context (it's not tacked onto an object), this would refer to the window object, which doesn't have getElementById.
In your HTML, change onclick="changeImage() to onclick="changeImage(this) and change your changeImage function to work with the argument passed instead:
function changeimage(img) {
if(img.src=="../../images/p1.gif")
img.src="../../images/p.gif";
else
img.src="../../images/p1.gif";
}
In the if statement it should be document.getElementById() not this.getElementById().
Though having said that, you can pass a reference to the clicked element in to your function:
<img onclick="changeImage(this);">
function changeImage(imgEl) {
if(imgEl.src=="../../images/p1.gif") {
imgEl.src="../../images/p.gif";
} else {
imgEl.src="../../images/p1.gif";
}
}
That way if all of your table rows are using the same two images they can all call the same function. Better than having the function hardcoded to a particular element's ID.
You need to call the function on click like this:
http://jsfiddle.net/4ca9m/
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<img id="special" src="http://nssdc.gsfc.nasa.gov/image/planetary/venus/gal_venus_37218.jpg" alt ="none">
<script>
$("img#special").click(function () {
if($(this).attr("src") == "http://nssdc.gsfc.nasa.gov/image/planetary/venus/gal_venus_37218.jpg")
{
$(this).attr("src", "http://gcaptain.com/wp-content/uploads/2011/04/image5.png");
}
else
{
$(this).attr("src", "http://nssdc.gsfc.nasa.gov/image/planetary/venus/gal_venus_37218.jpg");
}
});
</script>
</body>
</html>
It doesn't work because when you use a relative path like:
<img src="../../images/p1.gif" onclick="changeimage();" />
The browser may secretly turn it into an absolute path like:
<img src="http://example.com/somewhere/images/p1.gif" onclick="changeimage();" />
At least Internet Explorer 9 exposes this behavior. However, you shouldn't depend on this behavior.
There are at least two ways how you can solve this problem:
Use data- attributes. You add a custom attribute to your image tag:
<img src="../../images/p1.gif" data-image="p1" onclick="changeimage();" />
Then change your JavaScript function to this:
<script>
function changeimage()
{
if(this.getElementById('myimage').getAttribute("data-image") == "p1") {
document.getElementById('myimage').src="../../images/p.gif";
document.getElementById('myimage').setAttribute("data-image", "p");
} else {
document.getElementById('myimage').src="../../images/p1.gif";
document.getElementById('myimage').setAttribute("data-image", "p1");
}
}
</script>
Use a variable to accomplish the same thing as above.
<img src="../../images/p1.gif" onclick="changeimage();" />
And the JavaScript:
<script>
var image = "p1";
function changeimage()
{
if(image == "p1") {
document.getElementById('myimage').src="../../images/p.gif";
image = "p";
} else {
document.getElementById('myimage').src="../../images/p1.gif";
image = "p1";
}
}
</script>
I prefer the first method because it allows me to include all information about the image in the image itself and not in a variable declared several lines away.