get source of click in javascript? - javascript

I'm designing a webpage which uses very basic javascript.
Here's the code:
html:
<!DOCTYPE html>
<html>
<body>
<img id="apple" onclick="display()" src="images/apple.jpg" width="150" height="150">
<img id="pineapple" onclick="display()" src="images/pineapple.jpg" width="130" height="210">
<br><br>
<div id="description" style="width:300px;height:100px;border-top: 1px solid #000; border-bottom: 4px solid #000; border-left: 2px solid #000;
border-right: 4px solid #000;padding: 5px;"></div>
<br>
<button type="button" onclick="reset()">Reset</button>
<script type="text/javascript" src="obst.js"></script>
</body>
</html>
Here's the javascript:
function display()
{
document.getElementById("description").innerHTML="der Apfel - Apple<br>die Äpfel - Apples<br><br>Ein Apfel am
Tag hält den Arzt weg<br>- An apple a day keeps the doctor away";
}
function reset()
{
document.getElementById("description").innerHTML="";
}
Clicking on the image of the apple displays text in the description box. Clicking on the image of the pineapple displays some other text in the same place.
Instead of using different functions like apple(), pineapple() to insert text, I thought it would be easier to call a display function whenever something is clicked, and in the display function, if the script could identify the source of the click (that is, which image is clicked), it could insert text accordingly.
How do I go about this identifying the click source?

You can use this.id:
<img id="apple" onclick="display(this.id)" src="images/apple.jpg" width="150" height="150">
<img id="pineapple" onclick="display(this.id)" src="images/pineapple.jpg" width="130" height="210">
then catch the id:
function display(clicked_id)
{
alert(clicked_id);
}

You would pass this to the display() handler, then you can access the properties of the DOM element that received the click. Here is the fiddle: http://jsfiddle.net/dandv/BaNdS/. Essentially,
<img id="apple" onclick="display(this)" ... >
<img id="pineapple" onclick="display(this)" ... >
<script type="text/javascript">
function display(self) {
alert(self.id);
}
</script>

There is a easier way. Use a variable:
function selectFruit(fruit){
if(fruit == 'apple'){
.....
}else if(fruit == 'pinapple'){
.....
}
...
}

I would go in a somewhat different direction:
For each possible "term" have hidden block of text with the desired contents.
In each image tag add the ID of its proper placeholder as a rel attribute.
Have JavaScript running on page load, assigning the click event automatically.
Sample HTML would be:
<img id="apple" src="images/apple.jpg" rel="desc_Apple" width="150" height="150" />
<img id="pineapple" src="images/pineapple.jpg" rel="desc_Pineapple" width="130" height="210" />
<div class="item_placeholder" id="desc_Apple">
der Apfel - Apple<br>die Äpfel - Apples<br><br>Ein Apfel am
Tag hält den Arzt weg<br>- An apple a day keeps the doctor away
</div>
<div class="item_placeholder" id="desc_Pineapple">
der Apfel - Pineapple<br>die Äpfel - Pineapples<br><br>Ein Apfel am
Tag hält den Arzt weg<br>- An Pineapple a day keeps the doctor away
</div>
Don't forget CSS to make those hidden:
.item_placeholder { display: none; }
And finally the magic to bind them all:
window.onload = function() {
for (var i = 0; i < document.images.length; i++) {
var image = document.images[i];
var rel = image.getAttribute("rel");
if (rel && rel.length > 0) {
image.onclick = ItemImageClick;
}
}
};
function ItemImageClick() {
var rel = this.getAttribute("rel");
var placeholder = document.getElementById(rel);
if (placeholder) {
document.getElementById("description").innerHTML = placeholder.innerHTML;
} else {
alert("DEBUG - element not found " + rel);
}
}
Live test case.

Probably the simplest way:
var code, node = document.getElementById('description');
code = {
apple : "Apple",
pineapple: "Pineapple"
};
function display( src ) {
node.innerHTML = node.innerHTML ? "" : code[ src.id ] ;
}​
for ( var i in code ) {
document.getElementById( i ).onclick = function() { display( this ) };
}
Demo on jsFiddle

Simple and easy solution: pass arguments to the display function:
<img id="apple" onclick="display('apple');" …>
<img id="pineapple" onclick="display('pineapple');" …>
Better solution: Use the javascript-only (no JS in HTML markup) traditional or even the advanced event handling model. The listeners (which might be attached to multiple elements) will get passed an event object, from which you can determine which element was clicked. Example:
function clickHandler(eventObj) {
var elem = eventObj.target;
if (elem.nodeName.toLowerCase() == 'img' && elem.id)
display(elem.id);
}

Related

How to listen to a form field in JavaScript

I would like to be able to listen to a field in an input but without validating or clicking on anything
and if this field is empty then display an image
if the field is filled then no image is displayed
for that I will use el surval of the mouse above a div
here is my code but it seems to be a problem with the city condition in order to know if it is empty or not
I give you my code
I have been looking for several hours
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The onmousemove Event</h2>
<input class="form-control" type="text" name="ville" value="" id="ville" placeholder="" required="required" />
<div style ="width: 200px;
height: 100px;
border: 1px solid black;"onmousemove="myFunction(event)" onmouseout="clearCoor()"></div>
<img id="myImgaa" src="" width="107" height="98">
<script>
function myFunction() {
//alert(document.getElementsByName("ville"));
if (document.getElementsByName('ville') !== null && document.getElementsByName('ville') !== '')
{ document.getElementById("myImgaa").src = "https://www.w3schools.com/jsref/img_pulpit.jpg";}
else
{ document.getElementById("myImgaa").src = "";}
}
function clearCoor() {
}
</script>
</body>
</html>
You are getting a NodeList with getElementsByName. But you actually want a single element like getElementById.
You can use the following selector like: querySelector('[name="ville"]').
And you want actually want to check against it's value attribute. so your if statement should be as follow:
function myFunction() {
const ville = document.querySelector('[name="ville"]');
if (ville !== null && ville.value !== '')
{
document.getElementById("myImgaa").src = "https://www.w3schools.com/jsref/img_pulpit.jpg";
} else {
document.getElementById("myImgaa").src = "";
}
}

JavaScript - user selection function

I am new to JavaScript and I'm working on something. This is what I've reached so far and here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Image Editor V 1.0</title>
<script>
function changeOpacity(newValue) {
document.getElementById("span").innerHTML = newValue*100 +'%';
document.getElementById("image1").style.opacity = newValue;
}
var color = true;
function imgColor() {
if (color) {
document.getElementById("image1").style.WebkitFilter = "grayscale(100%)";
color = false;
} else {
document.getElementById("image1").style.WebkitFilter = "none";
color = true;
}
}
function colorImg() {
document.getElementById("image1").style.WebkitFilter = "none";
}
function greyImg() {
document.getElementById("image1").style.WebkitFilter = "grayscale(100%)";
}
function userImage() {
var link = document.getElementById("userImg").value;
document.getElementById("image1").src = link;
}
</script>
</head>
<body>
<button onclick="colorImg()">Colored</button>
<button onclick="greyImg()">Greyscale</button>
<button onclick="imgColor()" >Alternate</button><br><br>
Opacity :<input type="range" min="0" max="1" value="1" step="0.2" onchange="changeOpacity(this.value)"/>
<span id="span">100%</span> <br><br>
Try your own image! <input id="userImg" type="text" placeholder="Enter url here">
<button onclick="userImage()">Go!</button>
<br><br>
<img class="myImages" id="image1" src="image4.jpg">
<img class="myImages" id="image2" src="image2.jpg">
<img class="myImages" id="image3" src="image3.jpg">
</body>
</html>
So far, the "Colored", "Greyscale", and "Alternate" buttons along with the opacity slider work as intended only on the first image (image1.jpg). Also, when the user inputs his own image, it replaces the first image and the functions work on it as intended. Here is what am trying to do:
1 - Let the user select which of the three images he wants to edit by clicking on it, then apply a border around it and use it in the other functions (greyscale and opacity). Here's what I tried (but didn't work):
<img class="myImages" id="image1" src="image4.jpg" onclick="selectImg(this.id)">
<img class="myImages" id="image2" src="image2.jpg" onclick="selectImg(this.id)">
<img class="myImages" id="image3" src="image3.jpg" onclick="selectImg(this.id)">
function selectImg(imgID) {
document.getElementById("imgID").style.border = 50px;
}
2 - When the user inputs his own image, I want it to replace all the 3 images I have displayed by default.
Your help is greatly appreciated. Thanks in advance!
You are missing quotes both on the id and the 50px. But it is better to define a style for the selection.
Then let a click handler first remove that style from all the images, except the clicked image, where it should set that style. The functions .classList.add and .classList.remove can be used for that.
Where you currently have document.getElementById('image1'), you would do instead:
document.querySelector('.selected')
Then you should also make sure that the page loads with one image selected, i.e. with the selected class.
Some other improvements make sure that when changing the selection, the opacity slider is also brought in line with that image's current opacity setting.
Here is a snippet that does all that:
function changeOpacity(newValue) {
document.getElementById("span").textContent = newValue*100 +'%';
document.querySelector(".selected").style.opacity = newValue;
document.querySelector('input[type=range]').value = newValue;
}
function getOpacity() {
return parseFloat(document.querySelector(".selected").style.opacity || '1');
}
function isColor() {
return document.querySelector(".selected").style.WebkitFilter !== "grayscale(100%)";
}
function imgColor() {
document.querySelector(".selected").style.filter =
document.querySelector(".selected").style.WebkitFilter =
isColor() ? "grayscale(100%)" : "none";
}
function colorImg() {
if (!isColor()) imgColor()
}
function greyImg() {
if (isColor()) imgColor()
}
function userImage() {
document.querySelector(".selected").src = document.getElementById("userImg").value;
}
// Add this function, and call it on click on an image
function select(img) {
Array.from(document.querySelectorAll('.myImages')).forEach(
myImg => myImg === img ? myImg.classList.add('selected')
: myImg.classList.remove('selected')
);
// bring opacity slider in line with selected image
changeOpacity(getOpacity());
}
.selected {
border: 1px solid;
}
<button onclick="colorImg()">Colored</button>
<button onclick="greyImg()">Greyscale</button>
<button onclick="imgColor()">Alternate</button><br><br>
Opacity :<input type="range" min="0" max="1" value="1" step="0.2" onchange="changeOpacity(this.value)"/>
<span id="span">100%</span> <br><br>
Try your own image! <input id="userImg" type="text" placeholder="Enter url here">
<button onclick="userImage()">Go!</button>
<br><br>
<img class="myImages selected" id="image1" onclick="select(this)"
src="//cdn.sstatic.net/Sites/stackoverflow/company/img/logos/se/se-icon.png?v=93426798a1d4">
<img class="myImages" id="image2" onclick="select(this)"
src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a">
<img class="myImages" id="image3" onclick="select(this)"
src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/sf/sf-icon.png?v=6c3100d858bb">
First - you are not using that imgID, but String like that variable. Change to:
function selectImg(imgID) {
document.getElementById(imgID).style.border = 50px; //notice no quotes for imgID
activeImage = imgID; //set activeImage ID
}
And then when you are doing something to an image, don't use "image1", but activeImage that is global variable (defined outside and before functions).
And as for new uploaded image:
Put it into another div and work with such algorithm -
when (uploaded_new)
hide default pics
show DIV with new image
activeImage = uploadedPic

How to load the content of <h> element using jquery

I have a tag like:
<h3>Mobile
<img align="middle" alt="Edit" class="attEditCategory" src="/Images/edit.png">
<img align="middle" alt="Delete" class="attDeleteCategory" src="/Images/delete.png">
</h3>
I want to display the text of h3 ie "Mobile" in edit click button (on alert).
$(".attEditCategory").button().on("click", function (event) {});
Please help.
You can use $(this).parent().text() to get the text. Or $(this).closest('h3').text() if there could be more to the hierarchy than shown.
E.g.:
$(".attEditCategory").button().on("click", function (event) {
alert($(this).parent().text());
});
<link href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.min.js"></script>
<h3>Mobile
<img align="middle" alt="Edit" class="attEditCategory" src="/Images/edit.png">
<img align="middle" alt="Delete" class="attDeleteCategory" src="/Images/delete.png">
</h3>
If there could be text inside the buttons (e.g., button or a elements rather than img), $(this).parent().text() would include that text. So in that hypothetical case, it's more difficult (but still quite simple) to get just the text of the element itself and not the text of its children:
alert($(this).parent().contents().map(function() {
return this.nodeType === 3 ? this.nodeValue : ""; // 3 = text node
}).get().join(""));
$(".attEditCategory").button().on("click", function (event) {
alert($(this).parent().contents().map(function() {
return this.nodeType === 3 ? this.nodeValue : ""; // 3 = text node
}).get().join(""));
});
<link href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.min.js"></script>
<h3>Mobile
<a align="middle" alt="Edit" class="attEditCategory">edit</a>
<a align="middle" alt="Delete" class="attDeleteCategory">delete</a>
</h3>
try
$(".attEditCategory").on("click", function (event) {
alert($(this).parent().text())
});
DEMO
SInce the class is a child of the h3 use parent() to target the <h3> and text() to get the text
$(".attEditCategory").button().on("click", function (event) {
alert( $(this).parent().text());
});
$("h3").text();
Official documentation.
To access a specific h3 tag with a class or an id you do something like:
$("#foo").text(); //foo is the id
$(".foo").text(); //foo is the class
Simply:
$('h3').text();
And it returns just: "Mobile". It'll be enough to alert:
alert($('h3').text());

change image SRC and Style

Hi I want to rewrite an image Src and Style element.
The image tag has an element called "data-orig-file" wich has the url that I want to write to the src element.
I came up with this but I'm not good at javascript:
function changeImageSrc(img) {
var newurl= document.getElementById("img").getAttribute('data-orig-file');
var oldurl= document.getElementById("img").src;
document.getElementById("img").src = img.src.replace(oldurl, newurl);
}
Now Secondly I want to grab the "Style" element with it's values from the grandparent div of the image and write that style to the image instead of the original style.
Finally I want to do these two things on all images inside a container div on a page when it is loaded (I suppose).
Any help is greatly apreciated!!
Thanks
update:
what I came up with so far is this:
function ChangeImageSrc() {
var image=document.getElementById("img");
var div=document.getElementById("LastPost");;
for each (image in div) {
var newurl= document.getElementById("img").getAttribute('data-orig-file');
var oldurl= document.getElementById("img").src;
document.getElementById("img").src = img.src.replace(oldurl, newurl);
}
}
window.onload = function()
{
ChangeImageSrc();
};
I also tried it with an "onload" event on the body element like this (instead of the wondow.onload part):
onload="javascript:ChangeImageSrc()
Both don't work this far :(
Ok AffluentOwl, here's the HTML:
<div class="gallery-group images-1" style="width: 677px; height: 507px;">
<div class="tiled-gallery-item tiled-gallery-item-large">
<a href="http://i0.wp.com/www.mydomain.com/wp-content/uploads/..../../image.jpg" class="zoom">
<img data-attachment-id="5786" data-orig-file="http://www.mydomain.com/wp-content/uploads/..../../image.jpg" data-orig-size="1333,1000" data-medium-file="http://www.mydomain.com/wp-content/uploads/..../../image-300x225.jpg" data-large-file="http://www.mydomain.com/wp-content/uploads/..../../image-1024x768.jpg" src="http://i0.wp.com/www.mydomain.com/wp-content/uploads/..../../image.jpg?resize=1191%2C893" align="left" title="shelter-childrens-farm" data-recalc-dims="1" style="width: 73px; height: 9px;">
</a>
</div>
</div>
As you can see there is a CDN prefix to the url that I'm trying to loose (for good reasons, it's opposed to me by wordpress and doesn't work for me).
The second thing is about the style of the image tag, that's somehow set to the wrong dimensions so I want to grab the right size from the first div (top of code).
Here's how you replace an images' src attribute with a url stored in an attribute on the image called data-orig-file when the page loads.
<html>
<script>
function ChangeImageSrc() {
var div = document.getElementsByClassName("gallery-group images-1")[0];
var images = div.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
images[i].setAttribute("src", images[i].getAttribute("data-orig-file"));
images[i].setAttribute("style", div.getAttribute("style"));
}
}
window.onload = ChangeImageSrc;
</script>
<div class="gallery-group images-1" style="width: 500px; height: 500px;">
<div class="tiled-gallery-item tiled-gallery-item-large">
<img src="a.jpg" data-orig-file="b.jpg" id="image_id" style="width: 100px; height: 100px">
<img src="c.png" data-orig-file="d.jpg" id="image_id" style="width: 100px; height: 100px">
<img src="e.png" data-orig-file="f.png" id="image_id" style="width: 100px; height: 100px">
</div>
</div>
</html>
It would probably be helpful for you to look into the element selection functions in Javascript.
getElementById
getElementsByClassName
getElementsByTagName
querySelector
You may even like to use jQuery which makes selecting elements much easier. In jQuery you could replace the <script> code with the following for the same result as above:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function() {
var div = $(".gallery-group.images-1");
var images = div.find("img");
images.each(function() {
$(this).attr("src", $(this).attr("data-orig-file"));
$(this).attr("style", div.attr("style"));
});
});
</script>

switch multiple images on click

I have the code to switch an image back and forth and it works fine. However, I was wondering if there was a way to rewrite the script so I can use it in multiple places. This is my code currently:
function swaparrows(obj) {
var x=document.images
if (x[0].src.match('images/editloadout.png')) {
x[0].src="images/editloadoutopen.png";
}
else if (x[0].src.match('editloadoutopen.png')) {
x[0].src="images/editloadout.png";
}
}
<img src="images/editloadout.png" onclick="swaparrows()" />
which works for this one specific instance only. I would like it to work in multiple places with different pictures entirely.
Pass the two images in to the swap function, and use the actual clicked object's src:
function swaparrows(obj, i1, i2) {
var src = obj.getAttribute('src');
if (src.match(i1))
obj.setAttribute('src', i2);
else
obj.setAttribute('src', i1);
}
where the HTML is:
<img src="images/editloadout.png"
onclick="swaparrows(this, 'images/editloadout.png', 'editloadoutopen.png')" />
example: http://codepen.io/paulroub/pen/GoEBF
So you could use a case switch and decide based on the sender ID
Reference:http://www.w3schools.com/js/js_switch.asp
example:
function swaparrows(idTag) {
var ele = document.getElementById(idTag);
switch(idTag){
case("editLoadout"):
if (ele.src.match('images/editloadout.png')) {
ele.src="images/editloadoutopen.png";
}
else if (ele.src.match('editloadoutopen.png')) {
ele.src="images/editloadout.png";
}
break;
case("button2"):
if (ele.src.match('images/button2.png')) {
ele.src="images/button2open.png";
}
else if (ele.src.match('button2open.png')) {
ele.src="images/button2.png";
}
break;
}
}
<img id="editLoadout" src="images/editloadout.png" onclick="swaparrows('editLoadout')" />
<img id="button2" src="images/button2.png" onclick="swaparrows('button2')" />
Why not just use css and let javascript do more important stuff?
replace the background-color with background-image or whatever
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Switch</title>
<style>
.i{
width:32px;line-height:32px;
display:block;float:left;
text-align:center;
background-color:white;
}
.i:target{
background-color:green;
}
</style>
</head>
<body>
<a class="i" id="a" href="#a">a</a>
<a class="i" id="b" href="#b">b</a>
<a class="i" id="c" href="#c">c</a>
<a class="i" id="d" href="#d">d</a>
<a class="i" id="e" href="#e">e</a>
</body>
</html>
another approach is to set a js var with the current selected item and toggle the class of that.if you want an example just ask.any other questions just ask.
.. there are many ways to to what you want, your approach is not a good one.

Categories

Resources