Can styles be added using script code?

A kind member from this site has assisted me in fixing a script.

This initial segment of the code allows for the categorization and separation of blog articles by tags.

Is it feasible to incorporate CSS into this section of the code, where the tags Terror, Shounen, Ação each have a distinct color?

For instance: Terror - blue, Shounen - yellow, Ação - green

https://i.sstatic.net/Sxz02.jpg

The current script retrieves blogger content based on tags, but all columns share the same color. I wish to apply CSS to differentiate each one.

<div id="feed-list-container"></div>
<div style="clear:both;"></div>

<script type="text/javascript">
var multiFeed = {
    feedsUri: [
        {
            name: "Widget Title 1",
            url: "https://elfenliedbrazil.blogspot.com/",
            tag: "Terror"
        },
        {
            name: "Widget Title 2",
            url: "https://elfenliedbrazil.blogspot.com/",
            tag: "Shounen"
        },
        {
            name: "Widget Title 3",
            url: "https://elfenliedbrazil.blogspot.com/",
            tag: "Ação"
        }
    ],
    numPost: 3,
    showThumbnail: true,
    showSummary: true,
    summaryLength: 80,
    titleLength: "auto",
    thumbSize: 200,
    containerId: "feed-list-container",
    readMore: {
        text: "Read More",
        endParam: "?max-results=20"
    }
};
</script>
This is now the secondary part of the code.
<script>
/*<![CDATA[*/
var mf_defaults = {
  feedsUri: [{
    name: "JQuery Post",
    url: " ",
    tag: "JQuery"
  }, {
    name: "CSS Post",
    url: "",
    tag: "CSS"
  }, {
    name: "Blogger Widgets",
    url: " ",
    tag: "Widget"
  }],
  numPost: 4,
  showThumbnail: true,
  showSummary: true,
  summaryLength: 80,
  titleLength: "auto",
  thumbSize: 200,
  thumbWidth: 200, // new setting
  thumbHeight: 90, // new setting
  newTabLink: false,
  containerId: "feed-list-container",
  listClass: "list-entries",
  readMore: {
    text: "More",
    endParam: "?max-results=20"
  },
  autoHeight: false,
  current: 0,
  onLoadFeed: function(a) {},
  onLoadComplete: function() {},
  loadFeed: function(c) {
    var d = document.getElementsByTagName("head")[0],
      a = document.getElementById(this.containerId),
      b = document.createElement("script");
    b.type = "text/javascript";
    b.src = this.feedsUri[c].url + "/feeds/posts/summary" + (this.feedsUri[c].tag ? "/-/" + this.feedsUri[c].tag : "") + "?alt=json-in-script&max-results=" + this.numPost + "&callback=listEntries";
    d.appendChild(b)
  }
};
for(var i in mf_defaults) {
  mf_defaults[i] = (typeof(multiFeed[i]) !== undefined && typeof(multiFeed[i]) !== "undefined") ? multiFeed[i] : mf_defaults[i]
}

function listEntries(q) {
  var p = q.feed.entry,
    c = mf_defaults,
    h = document.getElementById(c.containerId),
    a = document.createElement("div"),
    d = "",
    l = c.feedsUri.length,
    n, k, m, g;
  for(var f = 0; f < c.numPost; f++) {
    if(f == p.length) {
      break
    }
    n = (c.titleLength !== "auto") ? p[f].title.$t.substring(0, c.titleLength) + (c.titleLength < p[f].title.$t.length ? "&hellip;" : "") : p[f].title.$t;
    m = ("summary" in p[f]) ? p[f].summary.$t.replace(/<br ?\/?>/g, " ").replace(/<.*?>/g, "").replace(/[<>]/g, "") : "";
    m = (c.summaryLength < m.length) ? m.substring(0, c.summaryLength) + "&hellip;" : m;
    g = ("media$thumbnail" in p[f]) ? '<img src="' + p[f].media$thumbnail.url.replace(/\/s72(\-c)?\//, "/w" + c.thumbWidth + "-h" + c.thumbHeight + "-c/") + '" style="width:' + c.thumbWidth + "px;height:" + c.thumbHeight + 'px;">' : '';
    for(var e = 0, b = p[f].link.length; e < b; e++) {
      k = (p[f].link[e].rel == "alternate") ? p[f].link[e].href : "#"
    }
    d += '<div class="post hentry"' + (!c.autoHeight ? ' style="height' + c.thumbHeight + 'px;overflow:hidden;"' : "") + ">";
    d += (c.showThumbnail) ? g : "";
    d += '<div class="post-title entry-title"><a href="' + k + '"' + (c.newTabLink ? ' target="_blank"' : "") + ">" + n + "</a></div>";
    d += '<div class="summary">';
    d += "<span" + (!c.showSummary ? ' style="display:none;"' : "") + ">";
    d += (c.showSummary) ? m : "";
    d += "</span></div>";
    d += '<span style="display:block;clear:both;"></span></div>'
  }
  d += "";
  d += '<div class="more-link"><a href="' + c.feedsUri[c.current].url.replace(/\/$/, "") + "/search/label/" + c.feedsUri[c.current].tag + c.readMore.endParam + '"' + (c.newTabLink ? ' target="_blank"' : "") + ">" + c.readMore.text + "</a></div>";
  a.className = c.listClass;
  a.innerHTML = '<div class="main-title"><h4>' + c.feedsUri[c.current].name + "</h4></div>" + d;
  h.appendChild(a);
  c.onLoadFeed(c.current);
  if((c.current + 1) < l) {
    c.loadFeed(c.current + 1)
  }
  if((c.current + 1) == l) {
    c.onLoadComplete()
  }
  c.current++
}
mf_defaults.loadFeed(0);
/*]]>*/
</script>

Answer №1

Building upon my previous comment:

Consider exploring the use of data attributes by referring to this resource: data attributes. Another approach could be adding a color code attribute to your json, and using inline CSS in your JavaScript to set the background-color for the div.

It's worth mentioning that there are various possibilities to address your question; my suggestion is just one method.

Your CSS file might resemble this structure:

div[data-tag='Terror'] {
    background-color: blue;
}
div[data-tag='Shounen'] {
    background-color: yellow;
}
div[data-tag='Ação'] {
    background-color: green;
}

You'd need to update your JavaScript to include a

data-tag="'+c.feedsUri[c.current].tag+'"
on your HTML element of interest.

The placement of the anchor tag may vary from your exact requirement, but it should give you a starting point in aligning with your intended direction.

a.innerHTML = '<div data-tag="'+c.feedsUri[c.current].tag+'" +class="main-title"><h4>' + c.feedsUri[c.current].name + "</h4></div>" + d;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to use jQuery to retrieve the style of an element based on a specific data attribute

I've been using bxSlider and I decided to create a unique custom pager using the pagerCustom option. My goal was to make the pager resemble a thumbnail pager, so I attempted to copy the style of each slide and attach it to the corresponding pager. For ...

Parsing JSON within an HTML document

It seems like what I'm attempting to do should be straightforward, but for some reason, I can't seem to get it to work? Let's say I have the following JSON file named jsonFile.json: { "level1": "elemet1", "level2": "element2", ...

The output of jQuery('body').text() varies depending on the browser being used

Here is the setup of my HTML code: <html> <head> <title>Test</title> <script type="text/javascript" src="jQuery.js"></script> <script type="text/javascript"> function initialize() { var ...

Switching hover behavior on dropdown menu for mobile and desktop devices

I have implemented a basic JavaScript function that dynamically changes HTML content based on the width of the browser window. When in mobile view, it removes the attribute data-hover, and when in desktop view, it adds the attribute back. The functionalit ...

Resolving JSON/AJAX Problem Arising from Server Session Expiration

I've encountered a frustrating issue with my website where ajax and json calls are not working after the session timeout of 120 minutes on the server side. When a user attempts to make a call from a loaded page after the timeout, the call goes through ...

Checking JavaScript files with TSLint

After spending many hours attempting to make this work, I still haven't had any success... I am wondering: How can I utilize TSLint for a .js file? The reason behind this is my effort to create the best possible IDE for developing numerous JavaScrip ...

AJAX POST responses may contain empty strings

When I send an AJAX POST request, I receive a JSON response: $.ajax({ url: ApiServiceVdc, type: 'POST', data: lepost, cache: false, success: function (data) { var detail = ''; detail += '<b>' + data.me ...

Initial React render fails to retrieve API data

I've encountered an issue during development where the page loads before the API data is sent. I attempted to use asynchronous functions, but it didn't resolve the problem as expected. I suspect that my approach may be incorrect. Here's a sn ...

Using Jquery to toggle the visibility of divs based on radio button selections

I am struggling to hide the divs with the radio buttons until their title is clicked on. However, I am facing issues as they are not showing up when their title is clicked on. Any assistance would be greatly appreciated. SPIKE <!DOCTYPE html> &l ...

Encountered an unexpected interpolation ({{}}) in column 3 of Data Bind RouterLink (Angular 2) that was expecting an expression

Encountering difficulties passing data to my routerLink. The goal is to change the route when the id reaches 4 within the ngFor loop. <input type="button" class="btn-cards" [ngClass]="getStyle(negociacao)" [routerLink]="['/{{negociacao.rota}}&apo ...

Easily move elements using a jQuery click animation

Having trouble animating a div's top position by -130px to move it off screen? Can't figure out why it's not working? I'm fairly new to jQuery/Javascript. I have a button/hyperlink with the ID #NavShrink. When clicked, I want the div # ...

Adjust the size of the font based on the screen resolution

What is the best way to adjust font size based on screen resolution so that text remains as a single line when the screen is small? For example: http://prntscr.com/2qa9ze <div class="centerbreaking"> <section id="breaking-news"> <div id ...

When you reach the end of the page, the loadMore function is triggered multiple times

On my webpage, I have a list of profiles that are displayed. When the user reaches the bottom of the page, more data should be loaded through the loadMore function. While the loadMore function itself works correctly, I am facing an issue with the listener. ...

Updating image properties with JQuery

My challenge involves dealing with an image that includes the following code: <img src="/Modules/Visualiser.php?template=1&text=testing"> The goal is to change the 'template' parameter based on a selection made in a dropdown menu. How ...

Tips for postponing the execution of inline javascript

Main page <script> $.ajax({ type: 'GET', url: 'ajax.php', context: document.body, success: function(data) { $("#content").html(data); } }); </script> <div id="content"></div> Ajax ...

Is there a way to eliminate the gap beneath each row of my Tic-Tac-Toe grid in Next.js with CSS styling?

What could be causing the space under every row in my CSS? I am currently developing a tic-tac-toe application using Next.js to enhance my skills. However, I have encountered an issue with the CSS where there appears to be a small space underneath each bo ...

Getting the value of a repeater label in JavaScript can be achieved by following these

Here is my javascript code: function btnEditClick() { alert(document.getElementById('<%=LblRefPhyID.ClientID %>').value); } <asp:Repeater ID="repeaterRefPhysicianList" runat="server"> <ItemTemplate> < ...

The function chartobject-1.render() is returning an error message stating: "Unable to locate the specified container within the document. This issue is occurring in the

I've encountered an issue while trying to integrate FusionCharts into my Vue.js project. Every time I attempt to render the charts within my components, I consistently run into this error. Here's a snippet of one of the components: <template&g ...

Determine the values from input fields that are constantly changing

Check out this snippet of HTML: <div class="container"> <div class="row"> <div class="col-md-12"> <div data-role="dynamic-fields"> <div class="form-inline"> ...

Encountering an unknown symbol '''' while trying to import a JSX file into a JavaScript file in a React application

Looking for some help with my JSX file, here's a snippet: Selector.jsx import React, { Component } from 'react'; import FormControl from '@material-ui/core/FormControl'; import InputLabel from '@material-ui/core/InputLabel&a ...