/    Sign up×
Community /Pin to ProfileBookmark

Newbie: Click on element and fire Javascript

Hi. I am trying to finish a personal website and have discovered I need Javascript to do something but alas I know no Javascript.

Am hoping somebody could help me solve my issue.

When a user clicks on particular HTML element, I would like to fire off some Javascript.

So where do I begin?

Thanks in advance!

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@sibertJan 12.2020 — https://www.w3schools.com/js/default.asp
Copy linkTweet thisAlerts:
@NachfolgerJan 15.2020 — Given the HTML markup:
``<i>
</i>&lt;div id='element-1'&gt;
Hey, this is element 1
&lt;/div&gt;<i>
</i>
`</CODE>

We can execute a function (anonymous or otherwise) when clicking <C>
element-1</C> by using a event listener:
<CODE>
`<i>
</i>document.getElementById('element-1').onclick = randomFucntion;

function randomFucntion() {
alert("Hey! You clicked me");
}<i>
</i>
`</CODE>

Full code:
<CODE>
`<i>
</i>&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Testing Onclick&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div id='element-1'&gt;
Hey, this is element 1
&lt;/div&gt;
&lt;script&gt;
document.getElementById('element-1').onclick = randomFucntion;

function randomFucntion() {
alert("Hey! You clicked me");
}
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;<i>
</i>
``
Copy linkTweet thisAlerts:
@VITSUSAJan 16.2020 — @SugarBush#1612965 Can you please share a snapshot of the code? It will more helpful for us to understand the errors.
×

Success!

Help @SugarBush spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...