-3

Is it possible to execute a block of javascript code when an element is clicked.

<a id="id-name" href="#">ABC</a>

I want to execute the following code only if above link is clicked

<script>
if(link-clicked){
  var marker = new google.maps.Marker({
    position: new google.maps.LatLng( 12.1223, 123.324 ),
    map: map,
    title: Some Location
  });
}
</script>

Note: just pure javascript

maverick
  • 141
  • 1
  • 13
  • how can I know there exists same question already. – maverick Aug 09 '18 at 11:31
  • 1
    Search bar at the top? Google Search? Duplicate questions are marked as duplicate to keep the site clear and not spammed. Your question would redirect to already answered question rather than having a million places with the same answers.. – Adrian Aug 09 '18 at 11:36

4 Answers4

0

You can use the href attribute to specify what code in javascript to run (ie the function to run). If you wish to keep the href you can also use the onclick attribute:

<a href="#" onclick="myCode();">Click me</a>

Here is an example using the href attribute:

function myCode() {
  console.log("Run my js code");
}
<a href="javascript:myCode();">Click me</a>
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

what you need is an event handler.

  • onchange=>An HTML element has been changed
  • onclick=>The user clicks an HTML element
  • onmouseover=>The user moves the mouse over an HTML element
  • onmouseout=>The user moves the mouse away from an HTML element
  • onkeydown=>The user pushes a keyboard key
  • onload=>The browser has finished loading the page

Using this type of event handler you can execute a block of javascript code when a specific event to a specific element occur.

EXAMPLE

function myFunction() {
    console.log(document.getElementById('d1').value);
}
<input type="number" id="d1" onclick="myFunction()">
Dev
  • 378
  • 2
  • 16
0

This is a good option...

<a id="id-name" href="#">ABC</a>

<script>
    var $link = document.getElementById('id-name');
    $link.addEventListener('click', getPosition);

    function getPosition () {
       var marker = new google.maps.Marker({
       position: new google.maps.LatLng( 12.1223, 123.324 ),
       map: map,
       title: Some Location
    }    
</script>
-1

The onClick attribute is one option.

<a id="id-name" href="#" onClick="myFunction()">ABC</a>
Ahorn
  • 649
  • 4
  • 19