Search code examples
javascriptpug

call a function on button click Jade


I am very new to Jade and NodeJS. I want to make a simple onclick function. I searched a lot on the internet but all the solutions I found didn't work with me I tried:

script.
    function clickme() {
      alert('sss')
    }

extends layout

block content
    button(onclick='clickme()')  click 

But, when I click on the button, I get an error:

clickme is not defined at HTMLButtonElement.onclick

I also tried:

var clickme = function() {
      alert('sss')
    }

anybody can help me?

I have another question, how can I define all the functions that I need in an extra javascript file and include it in my jade code and use its functions?


Solution

  • You need to include the script inside your block content:

    extends layout
    
    block content
      button(onclick='clickme()')  click
      script.
        function clickme() {
          alert('sss')
        }
    

    If you want the script in your head then you'd need to create another block for that in your layout.pug:

    doctype html
    html
      head
        meta(charset="utf-8")
        block head
      body
        block content
    

    Then you could do this:

    extends layout
    
    block head
      script.
        function clickme() {
          alert('sss')
        }
    
    block content
      button(onclick='clickme()')  click