Search code examples
javascriptarraysuserscripts

highlight keywords in a chatbox, how to add different styles to several keywords?


I'm editing a userscript that has a highlight function inside a chat box on a gaming site. I'm trying to make it so I can add keywords and different css styles to it. I'm looking for something that adds keywords into groups, so that I can make one style to several keywords in that group. And a different style to another group.

This is how it looks like

https://i.sstatic.net/7YEyH.png

dctools.checkForChatKeyword = function(elements) {
    if (GM_getValue("dct-options-hiflags") != null) {
        $(elements).highlight('flag')

            .highlight('keyword 1') 
            .highlight('keyword 2')
            .highlight('keyword 3')
            .highlight('keyword 4')
            .highlight('keyword 5')
            .highlight('keyword 6')
            .highlight('keyword 7');
    }

Is there a simple way to add css styles to these different keywords using arrays?


Solution

  • In general, (since you don't show the .highlight function code) you would:

    1. Create a series of jQuery style objects, like:

      var
          styleRedOnYellow  = {"color": "red",     "background": "yellow"}
        , styleWhiteOnBlack = {"color": "white",   "background": "black"}
        , styleLimeOnPink   = {"color": "lime",    "background": "pink"}
        , stylePuke_1       = {"color": "#EEF272", "background": "#97CC9A"}
      ;
      
    2. Then you can link keywords with styles using an associative array:

      var stylePerKeyword             = [];
      stylePerKeyword["keyword 1"]    = styleRedOnYellow;
      stylePerKeyword["apple"]        = styleRedOnYellow;
      stylePerKeyword["keyword 3"]    = styleLimeOnPink;
      stylePerKeyword["keyword 4"]    = styleLimeOnPink;
      stylePerKeyword["shoes"]        = stylePuke_1;
      
    3. Then inside the .highlight function, it can apply the styles to the wrapping nodes something like so:

      /*--- keywordParameter is the variable inside highlight() that 
          contains the particular keyword for this function call.
      */
      var styleToApply    = stylePerKeyword[keywordParameter];
      if (styleToApply) {
          /*-- wrappingNode is a jQuery around whatever highlight()
              wraps a word in to highlight it with. Probably a <span>.
          */
          wrappingNode.css (styleToApply);
      }
      else {
          console.log (
              '*** Unknown keyword, "' + keywordParameter 
              + '", in .highlight()'
          );
      }