Custom functions

I have two queries…

  1. i want to add onClick event in if else condition… can u provide a sample code.
  2. If i do some click event in page 1 of wix website… i want to make changes in a container box which is in different page … how to achieve this functionality. please guide me.
$w.onReady( ()=>{
    let tomato = {
       colour:"red",
       isAFruit:true
    }
    let colourChangeButton = $w("#myButton");
    if(tomato.isAFruit){
       colourChangeButton.onClick( (event, $w) => {
        //This sets your listener for whenever there is a click. 
        //This DOES NOT perform a click for you.
       
           tomato.colour = "green"
        } ); 
    }
}

@chris

i tried the above code and its not working…i also need to make changes in my container box which is in different page…is there anyway that we can handle an element from different page…

Pushkin,

What exactly wasn’t working?

For making changes that affect other pages, you will have to persist those changes somewhere, like a database, file or main memory. The most accessible location would be your website cookies. You can make a change like this.

 import {session} from 'wix-storage';
 $w.onReady( ()=>{ 
     let tomato = {        
          colour:"red",        
          isAFruit:true 
      } 
      
      let colourChangeButton = $w("#myButton"); 
      
      if(tomato.isAFruit){        
           colourChangeButton.onClick( (event, $w) => { 
           //This sets your listener for whenever there is a click.  
           //This DOES NOT perform a click for you.                    
           
           //To persist the data from the click, you can use session variable from the wix-session lass.
           session.setItem("colour","green");
       }); 
    } 
} 

Then, on page B where you’re checking for the new change, you can place the code in the onReady function.

import {session} from 'wix-storage';

 $w.onReady( ()=>{
 
     $w("#newTomatoColour").text= session.getItem("colour");
 });     

@chris
Thanks for your reply. Actually i am having a container box in page 2. I have not stored this container box in any database because i could not find any way to store container box in wix database.

Now in my page 1 i have a button. if i click that button the color of the container box in page 2 should change. here the container box is available only in page 2 and not in page 1. I want to control my container box properties which is available in page 2 from a button in page 1.

I will try out your above code.

Thanks.

@chris
please see my below code…let me know if i am missing something.

code on my page A to click the button and initiate color change.

import wixUsers from ‘wix-users’;
import wixData from ‘wix-data’;
import wixLocation from ‘wix-location’;
import {session} from ‘wix-storage’;
$w.onReady( function () {

let box3 = {
colour:“red”,
}

let submit = $w(‘#submit’);

if (userEmail === ‘abc@bridgestone.eu’ || userEmail === ‘def@live.com’ ) {

submit.onClick ( (event, $w) =>{
$w(‘#box122’).hide();
session.setItem(“colour”,“green”);
})
}
});

now in page B i have a container box where i m trying to push the changes stored in session.

import {session} from ‘wix-storage’;

 $w.onReady( **function**  () { 

//TODO: write your page related code here…
$w(“#box3”).style.backgroundColor= session.setItem(“colour”,“green”);
});

now when i am clicking the button submit in page A, it is nit changing the color of container box in page B…
Please guide me if i am missing something…

Thanks.

only one small bug that I see here,
In the second page you should write

$w(" #box3 ").style.backgroundColor = session.getItem(“color”)

@Moshe,

I tried with your correction still no effect… If possible can u provide me a sample code for container box for above requirement

Thanks!.

@Chris Derrell
I was able to achieve my requirement. Really thank you for your sample code.

I am facing one small issue though!!.. If any user is changing the color then when another users are logging in they can not see the colour change. I guess since i am storing the value temporarily in wix-session so it is not showing for other log in users… can u let me know that if any way is there where the changes made by one user can be seen to all the other users.

Thank you.

Aha! @ Pushkin, now you go into the realm of using the wix Database for persisted storage.

Before I answer, are you thinking immediate updates? Meaning as soon as I change the colour in my session here in Jamaica, it changes for you where you are in realtime?

Or is it that when you refresh the page, you’d see the change?

@Chris_Derrell
Let me refresh my requirement again. For my wix site i have given login functionality. Suppose we both are users for my site. Suppose You have made change in colour of a container box. when i will open the same site with my logging credentials i should see the changes made by you. Similarly if i make any changes to another container box you should see the change in colour. There is no refresh functionality for now. If any changes made then i have to close the site and open it again to see the latest changes made by any user.

now since you have mentioned about immediate updates, is it possible to do?
Please if you can provide any solution for my requirement.

Thanks!!.

@Pushkin,

Do you have a set list of items which are supposed to be tracked? Or is it everything?

@chris
No i dont have any data set or item list…this is straight container box .

Ok Great, I’m working on a little example for you. I’ll try to post by tomorrow this time

Haven’t forgotten you, having an issue with my Wix forums not loading.

Hi Chris. No problem buddy i faced the same something like bad gateway… if you got any solution for my issue you can mail me at pushkinsngh@live.com

Thanks.!

@chris-derrell
Just wanted to know if you have got any solution for my issue. If you can help me by today it will be of great help.

Thanks!.

Working on something here, check out your page here. https://derrellchristopher.wixsite.com/mysite

It’s not ready yet though, need to persist the changes.

Hey @pushkingeforce , the working page is live here. I hope it’s still in time for your original timeline.
https://derrellchristopher.wixsite.com/mysite/pushkin-s-page

The Code (~97 lines including comments)

// For full API documentation, including code examples, visit http://wix.to/94BuAAs
import wixData from 'wix-data';

let lastItemsSaved= {};
$w.onReady(function () {
 //TODO: write your page related code here...
    retrieveState($w("#page1"));
});

export function manageColorChange(event, $w) {
 //Add your code for this event here: 

 //For this, I've basically used the id of each button to represent its colour, for ease of example.

 let colour = event.target.id;

    $w("#box1").style.backgroundColor = colour;
    console.log($w("#box1").type);
    console.log(event.target.type);
    persistState($w("#box1"));
}

/**
 * Persist state is what passes the new box into the database.
 */
function persistState (item) {

 let updateItem = {
        page:$w("#page1").title,
        itemId:item.id,
        itemType:item.type,
        itemStyle:JSON.stringify(captureStyle(item))
    };
 if (!ie(lastItemsSaved)) {
 if(lastItemsSaved[item.id]!== undefined){//Checking if there has been any update for that item already on the page.
            updateItem._id = lastItemsSaved[item.id];  
        }
    }
    wixData.save("ItemStates", updateItem ).then(results=>{
        lastItemsSaved[results.itemId] = results._id;
    });
}

/**
 * This deals with the initialization of the page
 */
function retrieveState (pageObject) {
 let childIds = pageObject.children.map(value=>{ return value.id }); //By searching for the childrens id's we make it move faster.
 
    wixData.query("ItemStates").eq("page", $w("#page1").title).hasSome("itemId", childIds).limit(1).find()
    .then((results)=>{

 //Now that we've searched for all the items on this page who have a record in the database, we assign their styles back to the object
        results.items.forEach(itemFromDatabase=>{
            applyStyle(itemFromDatabase);
        })
    })    
}

/**
 * This is going to be your super method, which you extend for every object you want to capture.
 * What you'll do, if you want, is identify all the important style attributes from here.
 */
function captureStyle (wixElement) {
 let style = {};
 if(wixElement.type === "$w.Box"){
        style.backgroundColor = wixElement.style.backgroundColor;
        style.textColor = wixElement.style.color;
    }
 return style;   
}

/**
 * You may be wondering why I keep separating them out into functions for something 
 * that could be done in less lines. 
 * That's so you can extend it with ease.
 * 
 * This function takes in a database record, and applies its styles.
 */
function applyStyle (record) {
 // $w("#"+itemFromDatabase.itemId).style = itemFromDatabase.itemStyle;
    console.log(record);

 if(record.itemType === "$w.Box")
    {
 let wixElement = $w("#"+record.itemId), style = JSON.parse(record.itemStyle);
 try{
            wixElement.style.backgroundColor = style.backgroundColor ;
            wixElement.style.color = style.textColor;
        }
 catch (e){
            console.log(e.message);
        }
    }
}

const ie = (obj)=> Object.keys(obj).length === 0 && obj.constructor === Object;

Make sure to set your database read, write and update permissions to anyone.