Search code examples
javascriptvelo

How can I change background color on text element?


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.


Solution

  • I added a render on the item like this:

    $w.onReady(function () {
        // Write your JavaScript here
    
        $w('#dynamicDataset').onReady(() => {
            let rendered = $w('#text36').rendered
            if(rendered){
            let textVal =  $w('#text36').text
    
            if (textVal === "Available") {
                $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>`
            }
        }
    })})