I am trying to make a img that when it is clicked a JavaScript function is called.
I have searched on the web but haven't found anything that actually works (prob because of a mistake I made).
This code was made to pass JavaScript variables to a c# application.
Can anybody tell me what I am doing wrong?
<script type="text/javascript">
function exportToForm(a,b,c,d,e) {
window.external.values(a.value, b.value, c.value, d.value, e.value);
}
</script>
</head>
<body>
<img onclick="exportToForm('1.6','55','10','50','1');" src="China-Flag-256.png"/>
<button onclick="exportToForm('1.6','55','10','50','1');" style="background-color: #00FFFF">Export</button>
</body>
The onclick is added over an image tag inside HTML. The onclick event will make our image clickable. After a user clicks on the image, you can do whatever you want, like opening a new webpage, adding animations, changing an existing image with a new one, and so on. Inside the onclick , you can pass a function.
The most you could do is to trigger a background image change when hovering the LI. If you want something to happen upon clicking an LI and then staying that way, then you'll need to use some JS. I would name the images starting with bw_ and clr_ and just use JS to swap between them.
We can bind a JavaScript function to a div using the onclick event handler in the HTML or attaching the event handler in JavaScript. Let us refer to the following code in which we attach the event handler to a div element. The div element does not accept any click events by default.
This should work(with or without 'javascript:' part):
<img onclick="javascript:exportToForm('1.6','55','10','50','1')" src="China-Flag-256.png" />
<script>
function exportToForm(a, b, c, d, e) {
alert(a, b);
}
</script>
You should probably be using a more unobtrusive approach. Here's the benefits
- Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
- Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
- Progressive enhancement to support user agents that may not support advanced JavaScript functionality
Here's a jsfiddle demo
Your JavaScript
function exportToForm(a, b, c, d, e) {
console.log(a, b, c, d, e);
}
var images = document.getElementsByTagName("img");
for (var i=0, len=images.length, img; i<len; i++) {
img = images[i];
img.addEventListener("click", function() {
var a = img.getAttribute("data-a"),
b = img.getAttribute("data-b"),
c = img.getAttribute("data-c"),
d = img.getAttribute("data-d"),
e = img.getAttribute("data-e");
exportToForm(a, b, c, d, e);
});
}
Your images will look like this
<img data-a="1" data-b="2" data-c="3" data-d="4" data-e="5" src="image.jpg">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With