Home > Blockchain >  Get variable values from the DOM and use them as parameters in a webhook
Get variable values from the DOM and use them as parameters in a webhook

Time:02-21

I'm very new to JS and trying to work around a limitation in Webflow. I want to get some values from the webpage, and use those as parameters in a webhook.

The page structure could look something like this:

<body>
  <div id="job_ID" >123job</div>
  <div id="member_ID" >123member</div>
  <a href="webhook.link" >link</a>
</body>

I want to replace webhook.link with something like https://hook.integromat.com/XXXXX?member=123member&job=123job

I've been reading up about document.getElementById and document.createElement, but I'm honestly in way over my head. How do I use the job_ID and member_ID values from the page to use in a webhook?


Bonus Question

Also, is there a way to set it up so that clicking the button triggers the webhook instead of visiting the webhook URL?

CodePudding user response:

HTML

<body>
  <div id="job_ID" >123job</div>
  <div id="member_ID" >123member</div>
  <a href="webhook.link" >link</a>
</body>

JAVASCRIPT

window.addEventListener('load',function(){
let button = document.querySelector('.button'); 
button.addEventListener('click',function(event){
    event.preventDefault();
    event.target.href = getHref();
});
function getHref(){
    let jobID = document.querySelector("#job_ID").innerHTML;
    let memberID = document.querySelector("#member_ID").innerHTML;
    return `https://hook.integromat.com/XXXXX?member=${memberID}&job=${jobID}`;
}

Whenever you want to access a DOM element, you will need to wait for the window to load or javascript will not find the DOM elements. So, start your javascript inside the window load event.

The querySelector method of the document object is more efficent at selecting elements (in my opinion). It is formatted as:

document.querySelector('tagName'); //this will get an element by tag
document.querySelector('p');

document.querySelector('.className'); //Starting the string with a period will select an element by class.
document.querySelector('.output');

document.querySelector('#elementID'); //Starting the string with a # will get an element by it's ID attribute
document.querySelector('#job_ID');

Using querySelector will only return the FIRST element that it finds matching your selector (the stuff inside the parenthesis). If you need to select more than one element, use querySelectorAll

document.querySelectorAll('.hidden'); //will get all elements with class=hidden

In the button.addEventListener function above, you'll see the command

event.preventDefault();

This prevents the default action of an event from occurring, such as, an anchor tag redirecting to another page. Instead, you'll place the code for whatever you want your button to do right after the preventDefault statement.

Good Luck with your project!

  • Related