How can I change background color on text element?

68 Views Asked by At

I am attempting to use Wix's javascript to set the background color of a text element based on the value of that element.

Here's my code:

$w.onReady(function() {
  // Write your JavaScript here
  let textVal = $w('#text36').text

  if (textVal === "Available" || null) {
    $w('#text36').html = `<h1 style="background-color: green">${$w("#text36").text}</h1>`

  } else {
    $w('#text36').html = `<h1 style="background-color: red">${$w("#text36").text}</h1>`

  }

It is always "Red" and never green no matter the value of the text36 element. If I manually set the value of text36 it works so the issue is getting the value. This is coming from a CMS Field.

1

There are 1 best solutions below

1
emag78 On

If I have understood correctly, you should move your test code inside the onReady function of your dynamic dataset, in order to be sure that all data has been loaded before testing the text value:

$w.onReady(function() {
    // Write your JavaScript here

    $w('#dynamicDataset1').onReady(() => {
        let textVal = $w('#text36').text

        if (textVal === "Available" || null) {
            $w('#text36').html = `<h1 style="background-color: green">${$w("#text36").text}</h1>`
        } else {
            $w('#text36').html = `<h1 style="background-color: red">${$w("#text36").text}</h1>`
        }
    })
}