Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an onclick event to a div element

I saw a few similar topics which did help but I have specific problem and didn't manage to solve it alone so if anyone can help out I would appreciate it

I want to add onclick event to a div element.

HTML:

<div id="thumb0" class="thumbs" onclick="klikaj('rad1')"></div> 

JavaScript:

function klikaj(i) {     document.getElementById(i).style.visibility='visible'; } 

Wanted result: div with id="rad1" (which is hidden) turns visible, when clicked on div with id="thumb0".

This works when I add it to a button element but don't know how it goes with div elements.

like image 950
Slovenec Avatar asked Oct 18 '12 01:10

Slovenec


People also ask

Can I add onclick to a div?

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.

How do you call a function on a div click?

<div class="test">Click me! </div> $('div. test'). click(function(){ GetContent("xxx"); });

Can I add Onclick in CSS?

We cannot achieve the exact JavaScript onclick event in CSS. However, we can use a CSS trick to simulate an onclick event. The core concept behind this trick is the use of a checkbox and the label tag. We can attach them using the same value for the id attribute in the checkbox and the for attribute in label .


2 Answers

I'm not sure what the problem is; running the below works as expected:

<div id="thumb0" class="thumbs" onclick="klikaj('rad1')">knock knock</div> ​<div id="rad1" style="visibility: hidden">hello world</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ <script> function klikaj(i) {     document.getElementById(i).style.visibility='visible'; } </script> 

See also: http://jsfiddle.net/5tD4P/

like image 60
Ja͢ck Avatar answered Oct 02 '22 05:10

Ja͢ck


maybe your script tab has some problem.

if you set type, must type="application/javascript".

<!DOCTYPE html> <html>     <head>         <title>             Hello         </title>     </head>     <body>         <div onclick="showMsg('Hello')">             Click me show message         </div>         <script type="application/javascript">             function showMsg(item) {             alert(item);         }         </script>     </body> </html> 
like image 29
lingyfh Avatar answered Oct 02 '22 06:10

lingyfh