salman2301(1) - Copy.png
salman2301 logo transparent.png
  • Home

  • Services

  • Testimonials

  • Get a Quote

  • Forum

  • My theme

  • Examples

    • Suggest an app
    • Custom Menu bar
    • Multiple Filter
    • Print page
    • Horizontal scrolling
    • Wix Code Style
    • Wix video player code
    • Multiple Uploads
  • More

    Use tab to navigate through the menu items.

    {Salman}

    • Grey Facebook Icon
    • Grey Instagram Icon
    salman2301 logo transparent.png
    • Home

    • Services

    • Testimonials

    • Get a Quote

    • Forum

    • My theme

    • Examples

      • Suggest an app
      • Custom Menu bar
      • Multiple Filter
      • Print page
      • Horizontal scrolling
      • Wix Code Style
      • Wix video player code
      • Multiple Uploads
    • More

      Use tab to navigate through the menu items.
      To see this working, head to your live site.
      • Categories
      • All Posts
      • My Posts

      Forum

      Explore your forum below to see what you can do, or head to Settings to start managing your Categories.

      Wix code Advance

      Views 
      Posts6

      Feel free to share the code snippet to help the community

      Code Snippets

      Views 
      Posts2

      Reusable Code snippet

      New Posts
      • Salman2301
        May 16, 2021
        Build a realtime chat app in corvid
        Wix code Advance
        Wix release the new wix-realtime which allow developers to build interactive apps like chat app, multi-player game etc. So, In this example i will discuss how we can build a chat app where a user can send a message to person B and person B immediatly get the message. If you want to test it live here is the link: https://test.salman2301.com Overview Front-end we use custom element, which allows to show the message side by side and also with custome element, we can have a fix height and scroll bar so user can scroll to previous messages. We can use repeater for this but we need to use pagination or infinite scrolling which is why i didn't. On the Backend, we use wix-realtime API with datahook - datahook runs the code when a new row is inserted in the database. - realtime API allow us to do pub/sub ( publish/ subscriber) where sender or publisher send message to a channel and the reciever or subscriber can reciver the message. Dataflow If a user Person A send a message to Person B, the message will be inserted in the database and this runs the afterInsert data hook and the data hook use realtime api to publish to a channel, the name of the channel is same as the Person B user id. In this way, only the person B recieve the message and On the front-end, let's assume that the person B is online and we subscribe to the channel and the name of the channel Is the current user id. We get the user id from wix-user module wixUser.currentUser.id . Database Database Name: message Fields: field_key data from - USER_ID to - USER_ID message - Message Code // backend/data.js import  {publish}  from 'wix-realtime-backend' ; // datahook runs when a new row is inserted in the database // item contains inserted row information { from: "uuid", to:"uuid", message:"hello"} export function  message_afterInsert(item, context) { const  { from, to, message, _id } = item; const  channel = { name : to}; let  data = {         message, from,          _id     };  // publish which take a channel name and data. publish(channel, data, {includePublisher:  true }); return  item; } // Page code import * as  realtime  from "wix-realtime" ; import  wixUsers  from "wix-users" ; import  wixData  from "wix-data" ; import  { getUsers, getMe }  from "backend/getUsers.jsw" ; let  lastUserId, lastLoginEmail, lastPicture; let  userId = wixUsers.currentUser.id; let  owner; $w.onReady( function  () { // $w('#dataset1').onReady(init);   init();   $w( "#inSearch" ).onKeyPress((e)  =>  {     setTimeout(()  =>  { if  (e.key ===  "Enter" ) filterMem(); if  (e.key ===  "Escape" ) {         $w( "#inSearch" ).value =  "" ;         filterMem();        }     },  40 );   });   $w( "#ChatElement" ).setAttribute( "append-msg" ,     JSON.stringify({       user: {         name:  "salman" ,       },       msg:  " Hello this is a test" ,       date:  new  Date().toISOString(),       isOwner:  true ,     })   );   getMe().then((data)  =>  {     owner = data;   }); }); function  init() { // wix real time const  channel = { name: userId };   realtime.subscribe(channel, newMessage); // update UI   filterMem(); // events   $w( "#repeaterUser" ).onItemReady(($item, itemData, i)  =>  { let  { loginEmail, picture } = itemData;     $item( "#image1" ).src = picture;     $item( "#textEmail" ).text = loginEmail;   });   $w( "#containerUser" ).onClick((e)  =>  {     switchUser(e.context.itemId);   });   $w( "#btnSend" ).onClick(sendMessage);   $w( "#inMessage" ).onKeyPress((e)  =>  { const  { ctrlKey, key } = e; if  (key ===  "Enter"  && !ctrlKey) {       sendMessage();     }   }); } async function  filterMem() { let  inMember = $w( "#inSearch" ).value ||  undefined ;   getUsers(inMember)     .then((data)  =>  {       $w( "#repeaterUser" ).data = data.items; if  (!lastUserId) {         switchUser(data.items[ 0 ]._id);       }     })     .catch(console.error); } async function  switchUser(toUserId) {   lastUserId = toUserId;   $w( "#repeaterUser" ).onItemReady(($item, itemData, i)  =>  { let  { _id, loginEmail, picture } = itemData; if  (_id === toUserId) {       $item( "#imgCurrUser" ).show();       $w( "#textHeadUser" ).text =  `Connected to  ${ loginEmail } ` ;       lastLoginEmail = loginEmail;       lastPicture = picture;       refreshMsg();     }  else  {       $item( "#imgCurrUser" ).hide();     }   }); } async function  newMessage({ payload }) {   appendMsg(payload._id); } async function  refreshMsg() {   $w( "#ChatElement" ).setAttribute( "messages" ,  "[]" ); let  resMsgs =  await  wixData     .query( "message" )     .eq( "from" , userId)     .eq( "to" , lastUserId)     .or(wixData.query( "message" ).eq( "from" , lastUserId).eq( "to" , userId))     .ascending( "_createdDate" )     .find(); let  msg = resMsgs.items; let  username = lastLoginEmail.split( "@" )[ 0 ];   msg = msg.map((el)  =>  { let  isOwner = userId === el.from; let  userImage = isOwner ? owner.picture : lastPicture;     userImage = encodeURI(userImage); if  (!userImage.startsWith( "https://" )) userImage =  undefined ; return  {       _id: el._id,       isOwner: isOwner,       user: {         name: username,         image: userImage,       },       msg: el.message,       date: el._createdDate,       data: el,     };   });   $w( "#ChatElement" ).setAttribute( "messages" , JSON.stringify(msg)); if  (msg.length ===  0 ) {     $w( "#textNoMsg" ).show();   }  else  {     $w( "#textNoMsg" ).hide();   } } async function  appendMsg(msgId) { let  resMsgs =  await  wixData.query( "message" ).eq( "_id" , msgId).find(); let  message = resMsgs.items[ 0 ];   console.log({ resMsgs }); let  username = lastLoginEmail.split( "@" )[ 0 ]; let  isOwner = userId === message.from; let  userImage = isOwner ? owner.picture : lastPicture;   userImage = encodeURI(userImage); if  (!userImage.startsWith( "https://" )) userImage =  undefined ; let  msg = {     _id: message._id,     isOwner: isOwner,     user: {       name: username,       image: userImage,     },     msg: message.message,     date: message._createdDate,     data: message,   }; if  (!(lastUserId === message.from || lastUserId === message.to)) {     console.error( " No for the current user show alert!" ); return ;   }   $w( "#ChatElement" ).setAttribute( "append-msg" , JSON.stringify(msg)); } async function  sendMessage() { try  {     $w( "#btnSend" ).disable(); let  msg = $w( "#inMessage" ).value; if  (!msg)  return ; let  toInsert = {       from: userId,       to: lastUserId,       message: msg,     }; let  inserted =  await  wixData.insert( "message" , toInsert);     appendMsg(inserted._id);     $w( "#btnSend" ).enable();     $w( "#inMessage" ).value =  "" ;   }  catch  (e) {     console.log( "ERROR : " , e.message);     $w( "#btnSend" ).enable();     $w( "#inMessage" ).value =  "" ;   } } For the custome element check my github https://github.com/Salman2301/wix-chat-component
        2 comments2
        2
      • Salman2301
        Feb 20
        Wix Alert Web App
        Wix code Advance
        This post is to demo, how to add a alert at the side of the screen? Prerequisite This only work in domain connected premium wix site To test the app live goto https://www.test.salman2301.com/alert-web-component Check the video to quick demo For now the alert can only be trigger via code You can trigger the alert, in just few lines. Three steps 1) Add a Custom element 2) Add the Alert wix block to the site 3) Use code to trigger the app 1) Add a Custom element 1. Click on the add icon 2. Select Embed 3. Drag and Drop Custom element Setup custom element Click on the Custom element Select Choose Source Select Server URL for "Add your script file with:" Copy and paste the below URL for Server URL https://cdn.jsdelivr.net/gh/salman2301/wix-alert-component@master/dist/index.js Copy and paste "alerts-component" Tag Name Change the Custom element id to " CustomAlert " 2) Add the Alert wix block to the site 1) Click on this link -> http://wix.to/QcCAC7M 2) It will redirect to select the website to add, Select the site (see image below) 3) Select "I Understand" checkbox and click on "Confirm and Install" (see image below) 4) Now you can add from (+) > my Widget > "alertBySalman2301" (see image below) 5) Once the element is added to the page, Change the element ID to " widgetAlert " from propert panel 3) Use code to trigger the app : We Use code to trigger the alert to show a default alert // show alert $w( ' #widgetAlert ' ).alert( "Your Alert message here!" ) If you want to customise it, you can pass the Object {} instead of string //alert option, see below for more options let alertOption = { title: "Form failed", message: "Form didn't submit please try again" } // pass the alert options $w( ' #widgetAlert ' ).alert( alertOption ); Available Alert options, not only message is required property { // required field, message display in the alert message : "Alert message!." , // set color of alert based on success type : "success" , // "error" | "info" | "warn"|"success" // if it's false, user need to click on the close button autoClose : true , // you can also use any word e.g: "ACTION"| "Yes"|"No" closeLabel : "X" , // wait for 8 sec before autoClose, if it's set to true wait : 8 , // custom css style style : "" , // callback function trigger on autoClose or button click onClose : function (){}, // callback function trigger on button click onAction : function (){}, // brandColor set any hex, rgb color, refeclt the border brandColor : "#4BB543" , // redirect url on title or message clicked! knowMoreUrl : "https://salman2301.com" } You can goto the below URL to test the app https://www.test.salman2301.com/alert-web-component // You can either pass string or object // you can call any of the following property to show the alert // if you want to customise it, set more time or call for action // instead of string pass the object with the configuration $w( ' #widgetAlert ' ). alert ("your alert message"); $w( ' #widgetAlert ' ). alertError ("your alert message"); $w( ' #widgetAlert ' ). alertWarn ("your alert message"); $w( ' #widgetAlert ' ). alertInfo ("your alert message"); $w( ' #widgetAlert ' ). alertSuccess ("your alert message"); Note : to Use Alert up you need to select and set the custom element Just add this line to set the custom element on page ready $w( '#widgetAlert' ).setCustomElement($w( '#CustomAlert' )); Demo Code snippet : Let's show an warning on button click // wait for page ready $w.onReady( function () { // connect the web component with wix block $w( '#widgetAlert' ).setCustomElement($w( '#CustomAlert' )); // add a button $w( '#button2' ).onClick(()=>{ // show alert warning with message on click $w( '#widgetAlert' ).alertWarn( "Warning button is clicked!!" ) }); }); So, with just two line of code you can show the alert message Protip : If you are gonna use the alert app in multiple pages Right click the web component and select show on all page switch Also do the same for the Custom element. Now on the site page , connect the wix block and site element // wait for page ready $w.onReady( function () { // connect the web component with wix block $w('#widgetAlert').setCustomElement($w('#CustomAlert')); }); and on any page code call call the method ( alert | alertError | alertWarn | alertSuccess ) with the string or object $w( '#widgetAlert' ).alert( "Alert message here!!" ) Links Test Link - https://www.test.salman2301.com/alert-web-component Github Link - https://github.com/Salman2301/wix-alert-component Custom element - https://www.wix.com/corvid/reference/$w.CustomElement.html That's it, if you encounter any issue feel free to message me via salmanhammed77@gmail.com Happy Coding!
        3 comments3
        0
      • Salman2301
        Feb 23, 2019
        How to use this section?
        Code Snippets
        Check the tag of post #public or #backend If it's public Create a public .js file in your Wix account Name it as a "template.js" copy the main code function fullName(firstName, lastName){ return firstName + ' ' + lastName } and past it on template.js Final Public file //in template.js export function fullName(firstName, lastName){ return firstName + ' ' + lastName } Now you can reuse this function in any page Just by importing the module name import { fullName } from 'public/template'; // general import syntax import { moduleName } from 'public/filename.js'; Let say we have 2 input element with first name and last name After a button click We will show the full name in a text Final Page code //Importing module from template js file import { fullName } from 'public/template' $w.onReady(()=>{ $w('#btn').onClick(()=>{ let firstName = $w('#inFirstName').value; let lastName = $w('#inLastName').value; //Calling the module $w('#textDisplayFullName').text = fullName(firstName, lastName); }) }); - inFirstName - id of an input element - inLastName - id of an input element - textDisplayFullName - id of text element - btn - id of a button element
        0 comments0
        0

      © Copyright 2021 Salman2301. All rights reserved.