How to trigger a D3 transition only when the element scrolls into view

I have a tall web page filled with visualizations created with D3. I set up a transition that makes the bars in a bar chart “fall down” from the top of the plot over the course of 2 seconds.
I would like to trigger this transition() to happen only when the user scrolls this element into view (otherwise, it happens immediately when the page loads and the user doesn’t see the floating effect because it will take he/she a few minutes to scroll down to this element).

The parent element is named bar-chart-div.

Here is my code:

let data = [
{"color": "Blue", "plotValue": 11},
{"color": "Red", "plotValue": 20},
{"color": "Orange", "plotValue": 21},
{"color": "Purple", "plotValue": 30},
{"color": "Green", "plotValue": 35},
{"color": "Violet", "plotValue": 40},


        vis.margin = {top: 70, right: 90, bottom: 90, left: 80};
        vis.width = 800 - vis.margin.left - vis.margin.right;
        vis.height = 700 - vis.margin.top - vis.margin.bottom;

        // initialize the drawing area
        vis.svg = d3.select('#' + vis.parentElement).append('svg')
            .attr('width', vis.width + vis.margin.left + vis.margin.right)
            .attr('height', vis.height + vis.margin.top + vis.margin.bottom)
            .append('g')
            .attr('transform', `translate (${vis.margin.left}, ${vis.margin.top})`);


        // scales and axes
        vis.xScale = d3.scaleBand()
            .range( [ 0, vis.width ] )
            .padding(0.4);

        vis.yScale = d3.scaleLinear()
            .range( [ vis.height, 0 ] );

        vis.xAxis = d3.axisBottom()
            .scale(vis.xScale);

        vis.yAxis = d3.axisLeft()
            .scale(vis.yScale);

        // add chart title
        vis.svg.append('g')
            .attr('class', 'title bar-chart-title')
            .append('text')
            .text(vis.chartTitle)
            .attr('transform', `translate(${vis.width / 2 + 45}, -50)`)
            .attr('text-anchor', 'middle');

        // tooltip
        vis.tooltip = d3.select('body').append('div')
            .attr('class', 'tooltip')
            .attr('id', 'barChartTooltip');


        // create the axis groups
        vis.xAxisGroup = vis.svg.append('g')
            .attr('class', 'x-axis axis')
            .attr('transform', 'translate(0, ' + vis.height + ')');

        vis.yAxisGroup = vis.svg.append('g')
            .attr('class', 'y-axis axis');


        vis.xScale.domain(vis.data.map(function (d) { return d.color; }));
        vis.yScale.domain( [ 100, 0 ] );

        // draw the bars
        vis.bars = vis.svg.selectAll('.bar')
            .data(vis.data)

        vis.bars.exit().remove();

        vis.bars
            .enter()
            .append('rect')
            .attr('class', 'bar')
            .attr('x', d => vis.xScale(d.color))
//            .attr('y', d => vis.yScale(vis.height))
//            .attr('y', d => vis.yScale(0))
            .attr('y', d => d)
            .attr('width', vis.xScale.bandwidth())
            .on('mouseover', function(event, d) {
                d3.select(this)
                    .attr('stroke-width', '2px')
                    .attr('stroke', 'grey')
                    .attr('fill', 'blue')

                vis.tooltip
                    .style('opacity', 1)
                    .style('left', event.pageX + 20 + 'px')
                    .style('top', event.pageY + 'px')
                    .html(`
                    <div style='border: thin solid grey; border-radius: 5px; background: lightgrey; padding: 20px'>
                    <h3>${d.color}</h3>
                    <h4> ${100- d.plotValue.toLocaleString()}% decline </h4>
                    </div>
                                        
                    `)

            })
            .on('mouseout', function(event, d) {
                d3.select(this)
                    .attr('stroke-width', 1)
                    .attr('stroke', 'blue')
                    .attr('fill', function(d) {
                        return 'red'
                    })

                vis.tooltip
                    .style('opacity', 0)
                    .style('left', 0)
                    .style('top', 0)
                    .html(``);

            })
            .merge(vis.bars)
            .transition()
            .duration(2000)
            .attr('y', d => vis.yScale(d.plotValue) )
            .attr('height', function(d) { return vis.height - vis.yScale(d.plotValue); })
            .attr('fill', 'red')


        // add the axes
        vis.xAxisGroup
            .transition()
            .duration(500)
            .style('font-size', '15px')
            .style('color', 'blue')
            .call(d3.axisBottom((vis.xScale)))
            .selectAll('text')
            .attr('y', 30)
            .attr('x', -35)
            .attr('dy', '.35em')
            .attr('transform', 'rotate(-30)')
        ;

        vis.yAxisGroup
            .transition()
            .duration(500)
            .style('font-size', '15px')
            .style('color', 'blue')
            .call(d3.axisLeft(vis.yScale));

        vis.text = vis.svg.selectAll('.text')
            .data(vis.data)

        vis.text
            .enter()
            .append('text')
            .attr('class', 'text')
            .attr('text-anchor', 'middle')
            .attr('x', d => vis.xScale(d.color) + 27)
            .attr('y', d => vis.yScale(100- d.plotValue) + 20)
            .text( function (d) {
                return '-' + (100 - d.plotValue) + '%';
            })
            .style('font-weight', 600)
            .style('fill', 'black')

Thanks in advance for your help!

Javascript for card shuffle failing

Over my head with javascript. I’m trying to get the cards to shuffle when clicking next.

Currently, it moves forward with one random shuffle and stops. Back and forward buttons then no longer work at that point.

Please help—many thanks.

When I’m lost and unsure what sample of the code to pinpoint, the captions go up to 499. The sample is also here: https://rrrhhhhhhhhh.github.io/sentences/

Very new to javascript. So any help is greatly appreciated. Very open to better ways to achieve this???

How I have it set up:
HTML:

var r = -1;

var mx = 499; // maximum
var a = new Array();

function AddNumsToDict(){
    var m,n,i,j;
    i = 0;
    j = 0;
    while (i <= 499)
    {
       m = (500 * Math.random()) + 1;
       n = Math.floor(m);

       for (j=0;j<=499;j++)
       {
         if (a[j] == (n-1))
         {
       j = -1;
           break;
         }
       }
       if (j != -1)
       {
     //a.push(n-1);
         a[i] = (n-1);
         i++;
     j=0;
       }

    }
    return;

}

function startup()
{
  writit('SENTENCES<br><br><br>Robert Grenier', 'test');
  SetCookie("pg", -1);
  AddNumsToDict();

}

function SetCookie(sName, sValue)
{
  document.cookie = sName + "=" + escape(sValue) + ";"

}

function GetCookie(sName)
{
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    // a name/value pair (a crumb) is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0])
      return unescape(aCrumb[1]);
  }

  // a cookie with the requested name does not exist
  return null;
}
function doBack(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');

//if ((oNxt) && (oPrev))
//{
    var num = GetCookie("pg");
    if (num == mx){ //maximum
      SetCookie("pg",parseInt(num) - 1);
      num = GetCookie("pg");
    }
//    oNxt.disabled = false;

//    if (num <= 1){
//      oPrev.disabled = true;
//    }
    if (num >= 1){
      num--;
      writit(Caption[a[num]], 'test');
      SetCookie("pg",num);
    }
//}
}

function doNext(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
//  if ((oNxt) && (oPrev))
//  {
  var num = GetCookie("pg");
//  if (num > -1){
//    oPrev.disabled = false;
//  }
//  else{
//    oPrev.disabled = true;
//  }
//  if (num >= parseInt(mx)-1){  //maximum - 1
//    oNxt.disabled = true;
//  }
//  else {
//    oNxt.disabled = false;
//  }
  if (num <= parseInt(mx)-2){
    num++;
    writit(Caption[a[num]],'test');
    SetCookie("pg",num);
  }
//  }
}
function writit(text,id)
{
        if (document.getElementById)
        {
                x = document.getElementById(id);
                x.innerHTML = '';
                x.innerHTML = text;
        }
        else if (document.all)
        {
                x = document.all[id];
                x.innerHTML = text;
        }
        else if (document.layers)
        {
                x = document.layers[id];
        l = (480-(getNumLines(text)*8))/2;
        w = (764-(getWidestLine(text)*8))/2;
                text2 = '<td id=rel align="center" CLASS="testclass" style="font:12px courier,courier new;padding-left:' + w.toString() + 'px' + ';padding-top:' + l.toString() + 'px' + '">' + text + '</td>';
                x.document.open();
                x.document.write(text2);
                x.document.close();
        }
}
function getNumLines(mystr)
{
  var a = mystr.split("<br>")
  return(a.length);
}
function getWidestLine(mystr)
{
  if (mystr.indexOf("&nbsp;") != -1)
  {
    re = /&nbsp;*/g;
    mystr = mystr.replace(re,"Z");
    //alert(mystr);
  }
  if (mystr.indexOf("<u>") != -1)
  {
    re = /<u>*/g;
        mystr = mystr.replace(re, "");
        re = /</u>*/g;
    mystr = mystr.replace(re, "");
  }

  if (mystr.indexOf("<br>") != -1)
  {
    var ss, t;
    var lngest;
    ss = mystr.split("<br>");
    lngest = ss[0].length;
    for (t=0; t < ss.length; t++)
    {
      if (ss[t].length > lngest)
      {
        lngest = ss[t].length;
      }
    }
  }
  else {
    lngest = mystr.length;
  }
  return(lngest);
}
// -->

</script>
<body bgcolor="gainsboro" onload="startup();">


<table bgcolor="white" border height="480px" width="764px" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table nowrap>
<tr>
<td><img width="700px" height="1px" src="./resources/images/w.gif"></td>
<td>
<div class="testclass" id="test"></div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<center>
<form>
<p>

<input type="button" onclick="doBack(); return false" value="Back">
<input type="button" onclick="doNext(); return false" value="Next">

JS:

var _____WB$wombat$assign$function_____ = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };
if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }
{
  let window = _____WB$wombat$assign$function_____("window");
  let self = _____WB$wombat$assign$function_____("self");
  let document = _____WB$wombat$assign$function_____("document");
  let location = _____WB$wombat$assign$function_____("location");
  let top = _____WB$wombat$assign$function_____("top");
  let parent = _____WB$wombat$assign$function_____("parent");
  let frames = _____WB$wombat$assign$function_____("frames");
  let opener = _____WB$wombat$assign$function_____("opener");

function CaptionArray(len) {
    this.length=len
}
Caption = new CaptionArray(499);
Caption[0] = "leaf and the ants as latterly"
Caption[1] = "thought<br>living in<br>Davis would<br>be ok"
Caption[2] = "sure arm today"
Caption[3] = "AMY<br><br>no we<br>both do<br>different<br>songs together"
Caption[4] = "much of anything she doesn't like that at all"
Caption[5] = "SUNG AS LAKE<br><br><br>that never wanted back to come"
Caption[6] = "five sound shut doors"
Caption[7] = "oh<br>my nose is<br>so<br>red<br>Obediah<br>dear"
Caption[8] = "these<br>cubes<br>have been<br>on the floor"
Caption[9] = "sweating importunate"
Caption[10] = "all over noises phone rings"
Caption[11] = "I think this is the water supply for Lake Johnsbury"
Caption[12] = "Paw so greasy"
Caption[13] = "BLACK & WHITE RAIN<br><br><br>clear water grey drops<br><br><br>on windshields in a line<br><br><br>of cars progressing slowly<br><br><br>with windshield wipers wiping"
Caption[14] = "EMILY<br><br>Roger,<br><br>are you<br><br>thinking of me"
Caption[15] = "STICKS<br><br><br>rhythm is inside the sound like another"
Caption[16] = "I think their dog always barks when coming back from the woods"
Caption[17] = "weren't there<br><br>conversations"
Caption[18] = "LOOKING AT FIRE<br><br><u>ashes</u> to ashes<br><br>looking at the fire<br><br>at has been added"
Caption[19] = "a the bank"


}

How to call a function in a reactive from another page?

i have 2 pages : page1.html and page2.htmlpage2.html

<script type="model">
  import {createApp, nextTick, reactive} from './js/petite-vue.es.js'
  const store = reactive({
     welcomeUser() {
        console.log('Hello User');
     }
  })
</script>

The problem is :

i want to call the welcomeUser() function in my page1.html

in my page1.html i’ve created a promise function that load page2.html before page1.htmland tried to call welcomeUser()

store.welcomeUser()

but Im getting an error in my browser’s console saying

store is not defined

what’s the problem ? is there a way to call a function in petite vue from another page ?

Question about where the JSON global object comes from

I am following a tutorial which introduced the global JSON object to stringify objects, in the tutorial they mention that this JSON object and it’s methods is provided by the browser. I’ve also looked at the MDN page for JSON and they list it as a standard built in object.

I’m trying to understand if an object such as this is the same as the Date or Math objects and is built into Javascript or is it something extra that is provided by browsers implementing it?

Vue3 Nuxt3 hide div on button click

I am using nuxt3 and I am trying to hide a div on button click.
I know that I can do @click="errorMsg = !errorMsg, but I specifically want it to call a function that changes the data and toggles the visibility. Because eventually it’s gotta trigger when a user does something wrong.

The way I have it at the moment it’s doing nothing and I do not know why. When I change the value like @click="errorMsg = !errorMsg it works.

This is how my template looks like:

<template>
 <div v-if="errorMsg" >
    <p>fout</p>
  </div>

  <button @click="toggle">
    klik
  </button>
</template>

The function itself:

<script setup lang=ts>
let errorMsg = ref(false)

function toggle(){
  errorMsg = ref(!errorMsg)
}

</script>

How to use Context API with useParams

I have an api with details of a farm and I want to show them in different components using an id. Like the data is used in many components and I want to use Context API to display the data in the components.

So here is the code that fetches the data

let navigate = useNavigate();
const [farm, setFarm] = useState('');
const { username } = useParams();
const { farmId } = useParams();
const [isLoading, setIsLoading] = useState(true);
const user = React.useContext(UserContext);

useEffect(() => {

    let isMounted = true;

    axios.get(`/api/farm/${username}/${farmId}`).then(res => {
        if (isMounted) {
            if (res.data.status === 200) {
                setFarm(res.data.farm);
                setIsLoading(false);
                console.warn(res.data.farm)
            }
            else if (res.data.status === 404) {
                navigate('/');
                toast.error(res.data.message, "error");
            }
        }

    });

    return () => {
        isMounted = false
    };
}, []);

The username is okay because I will use the user context to get the user details.
Now, how do Use this from a context into the components, because I have tried, and it is not working.

How to hide collapsible navbar menu when clicking outside of it (Bootstrap 5)?

I have a collapsible navbar menu:

<div class="collapse navbar-collapse" id="navbarMenu">
   .. menu items ..
</div>

I want to hide it whenever a user clicks outside of it (so not just when he clicks the menu button again):

$(document).ready(function() {
    const collapseElementList = document.querySelectorAll('.collapse'); //SelectorAll just for the test           
    navbarCollapsible  = collapseElementList[0];        
    $('body').on("click", function() {
        navbarCollapsible.hide();
    });
});

But I get: Uncaught TypeError: navbarCollapsible.hide is not a function

generate random Poisson numbers with given expected value M(x)

I need to generate a hundred random numbers and each number max value is 80;

I can’t figure out how to connect Poisson method with expected value that equals 28.

that means sum is 28 * 100 = 2800. So M(x) is 28.

but that means I need to track every generated number before?

I noticed that D(x) equals M(x) but in some examples these values is different.

I found this answer it can help me but it doesn’t compile

const maxLimit = 80;
function poissonRandomNumber(lambda) {
  var L = Math.exp(-lambda),
    k = 0,
    p = 1;
  do {
    k = k + 1;
    p = p * Math.random();
    console.log(p, k);
  } while (p > L);

  return Math.min(k, maxLimit);
  // return k - 1;
}

var res = poissonRandomNumber(maxLimit);
console.log("res", res);

How to change the keys in nested array of objects

Following is my array and I need to replace the keys as “name” to “title” and “Email” to “subtitle”.

I tried some ways but it’s not fulfilled my requirement. Could please provide any solution about this.

Thanks in advance

const newUpdatedList = [];
  resArr.forEach((res) => {
    const obj = {
      title: res.name,
      subtitle: res.attributes.Email
    };

    if (res.children) {
      const newList = res.children.map((ch) => {
        return {
          title: ch.name,
          subtitle: ch.attributes.Email,
        };
      });
      obj.children = newList;
    }
    newUpdatedList.push(obj);

});

const resArr= [
{
“user_id”: “f7ba4795-d279-4c38-9a84-7a49522c50a2”,
“name”: “Harsha ABC”,
“custom_id”: “mani78989-1gfqv04bo”,
“attributes”: {
“Email”: “[email protected]”,
“Role”: “admin”
},
“children”: [
{
“user_id”: “d748037a-b445-41c2-b82f-4d6ee9396714”,
“name”: “Lavaraju Allu”,
“custom_id”: “mani78989-1gfqv472q”,
“attributes”: {
“Email”: “[email protected]”,
“Role”: “Manager”
},
“children”: [
{
“user_id”: “881c7731-b853-4ebc-b271-8f9e9215f7a1”,
“name”: “Ramesh Allu”,
“custom_id”: “mani78989-1gh14i13t”,
“attributes”: {
“Email”: “[email protected]”,
“Role”: “Retailer”
},
“children”: [
{
“user_id”: “f7ba4795-d279-4c38-9a84-7a49522c50a2”,
“name”: “Harsha ABC”,
“custom_id”: “mani78989-1gh15nrev”,
“attributes”: {
“Email”: “[email protected]”,
“Role”: “Delivery Manager”
},
“children”: []
}
]
}
]
},
{
“user_id”: “550cc296-d7e4-44fb-9d62-4c6755b3f6f2”,
“name”: “Suresh Kunisetti”,
“custom_id”: “mani78989-1gfqv6idi”,
“attributes”: {
“Email”: “[email protected]”,
“Role”: “Super Admin”
},
“children”: [
{
“user_id”: “45cf19f8-36c1-4669-9333-1226c4f7b66b”,
“name”: “Harish Three”,
“custom_id”: “mani78989-1ggv5vffb”,
“attributes”: {
“Email”: “[email protected]”,
“Role”: “Delivery Manager”
},
“children”: []
}
]
},
{
“user_id”: “2c8535be-5fe7-40f0-892f-0f9bcffe0baa”,
“name”: “Sandeep Bbb”,
“custom_id”: “mani78989-1gh14m5p4”,
“attributes”: {
“Email”: “[email protected]”,
“Role”: “Delivery Manager”
},
“children”: []
},
{
“user_id”: “881c7731-b853-4ebc-b271-8f9e9215f7a1”,
“name”: “Ramesh Allu”,
“custom_id”: “mani78989-1gh14pc6p”,
“attributes”: {
“Email”: “[email protected]”,
“Role”: “Manager”
},
“children”: []
}
]
}
]

Expected output is

const resArr= [
{
“user_id”: “f7ba4795-d279-4c38-9a84-7a49522c50a2”,
“title”: “Harsha ABC”,
“custom_id”: “mani78989-1gfqv04bo”,
“attributes”: {
“subtitle”: “[email protected]”,
“Role”: “admin”
},
“children”: [
{
“user_id”: “d748037a-b445-41c2-b82f-4d6ee9396714”,
“title”: “Lavaraju Allu”,
“custom_id”: “mani78989-1gfqv472q”,
“attributes”: {
“subtitle”: “[email protected]”,
“Role”: “Manager”
},
“children”: [
{
“user_id”: “881c7731-b853-4ebc-b271-8f9e9215f7a1”,
“title”: “Ramesh Allu”,
“custom_id”: “mani78989-1gh14i13t”,
“attributes”: {
“subtitle”: “[email protected]”,
“Role”: “Retailer”
},
“children”: [
{
“user_id”: “f7ba4795-d279-4c38-9a84-7a49522c50a2”,
“title”: “Harsha ABC”,
“custom_id”: “mani78989-1gh15nrev”,
“attributes”: {
“subtitle”: “[email protected]”,
“Role”: “Delivery Manager”
},
“children”: []
}
]
}
]
},
{
“user_id”: “550cc296-d7e4-44fb-9d62-4c6755b3f6f2”,
“title”: “Suresh Kunisetti”,
“custom_id”: “mani78989-1gfqv6idi”,
“attributes”: {
“subtitle”: “[email protected]”,
“Role”: “Super Admin”
},
“children”: [
{
“user_id”: “45cf19f8-36c1-4669-9333-1226c4f7b66b”,
“title”: “Harish Three”,
“custom_id”: “mani78989-1ggv5vffb”,
“attributes”: {
“subtitle”: “[email protected]”,
“Role”: “Delivery Manager”
},
“children”: []
}
]
},
{
“user_id”: “2c8535be-5fe7-40f0-892f-0f9bcffe0baa”,
“title”: “Sandeep Bbb”,
“custom_id”: “mani78989-1gh14m5p4”,
“attributes”: {
“subtitle”: “[email protected]”,
“Role”: “Delivery Manager”
},
“children”: []
},
{
“user_id”: “881c7731-b853-4ebc-b271-8f9e9215f7a1”,
“title”: “Ramesh Allu”,
“custom_id”: “mani78989-1gh14pc6p”,
“attributes”: {
“subtitle”: “[email protected]”,
“Role”: “Manager”
},
“children”: []
}
]
}
]

Why are my posts fetched with apollo cached (or so it seems) and how can I avoid this?

I’m learning React js and Graphql. My idea was to query my posts using @apollo/client in my getServerSideProps function, put them in a prop and pass them to the state.

When adding a mutation that deletes a post I made it so it will set the state again so the deleted post will disappear. However, what ends up happening is that the post will disappear, and will be deleted from the database. But when I refresh the page it is back again. Since it is deleted from the DB and getServerSideProps is supposed to run on every request I’m thinking maybe it has to do with caching but I have not been able to google a solution so far. Any help as to what’s going on and how I could fix it would be appreciated.

export default function Posts({posts}) {
    const [postList, setPostList] = useState(posts);

    const postDeleted = ((deletedPostId)=> {
        setPostList(postList.filter((post) => {
            return post.id !==  deletedPostId;
        }))
    })

    return (
        <div>
            <h1 className={"text-4xl mb-5"}>Posts</h1>

            <div className="flex flex-wrap">
                {postList.map((post) => (
                    <div key={post.id} className={"md:w-1/3"}>
                        <PostPreview postDeleted={postDeleted} post={post}/>
                    </div>
                ))}
            </div>
        </div>
    )
}

export async function getServerSideProps() {
    const { data } = await client.query({
        query: gql`
        query Posts {
          posts {
            id
            title
            slug
          }
        }
      `,
    });

    return {
        props: {
            posts: data.posts,
        },
    };
}

clearInterval is not working on variables [duplicate]

The clear interval is working when i put the exact value to it but it’s not working when i put variable to it.

setInterval(() => {
        numbers.forEach(dataNum=>{
            let val = dataNum.dataset.progress;
            if (counter == val) {  //when i put 50 or any exact value here, counter is working properly
                clearInterval()
            } else {
                counter = counter+1;
                numbers.forEach(num=>{
                    num.innerHTML = `${counter}%`
                });
            }
        });
        
    }, 20);

Receiving different values of the same input/select in Javascript

I’m facing a little weird problem when select all inputs or selects with a specific attribute. In my DOM I have four inputs or selects that I want to select but the’re coming in duplicate and one comes with values and another one comes empty.

You guys have some idea of whatahell I’m facing?

My HTML code:

<div class="row align-items-center">
            <label for="m125-nome" class="col-sm-5 col-lg-3 col-form-label"><span class="px-1 red">*</span>Nome:</label>
            <div class="col-sm-6 col-lg-3">
              <input type="text" name="m125-nome" id="m125-nome" value="{{atom_data:nome}}" class="form-control form-control-sm" mandatory="dadosBasicos">
            </div>
            <label for="m125-nomeCivil" class="col-sm-5 col-lg-3 col-form-label"><span class="px-1 red">*</span>Nome Civil:</label>
            <div class="col-sm-6 col-lg-3">
              <div class="input-group">
                <label class="input-group-text py-1 px-2">
                  <span class="pe-2">Social</span> <input class="form-check-input mt-0 ps-2" type="checkbox" value="" aria-label="social">
                </label>
                <input type="text" name="m125-nomeCivil" id="m125-nomeCivil" value="{{atom_data:nomeCivil}}" class="form-control form-control-sm" mandatory="dadosBasicos">
              </div>
            </div>
          </div>

B4 send the inputs to validate these fields I verify if they’re in a specific scope, if yes I send the mandatory value to the function below.
Function that consumes these fields:

validarCamposObrigatorios: function (args = '') {
        console.table(['MANDATORY ARGS', args])
        var validacaoResult = {};
        var mensagemValidacao = '';

        if (args == '') {
            console.log('caiu required')
            var validarCampos = document.querySelectorAll('[required]')
        } else {
            console.log('caiu mandatory')
            var validarCampos = document.querySelectorAll(`[mandatory='${args}']`)
        }

        console.log(validarCampos)

        console.table(validarCampos.forEach(e=> console.table(e.value)))
        // Para cada elemento a ser validado
        validarCampos.forEach((e) => {
          if (e.value === '') {
            let mensagemCampo = document.querySelector(`label[for=${e.id}]`).innerText.replaceAll('*', '- ').replaceAll(':', '') + 'n'
            mensagemValidacao += mensagemCampo
            e.focus()
          }
        })

        // Caso a mensagem de validação não esteja vazia
        if (mensagemValidacao != ''){
            mensagemValidacao = 'Os seguintes campos são obrigatórios:nn' + mensagemValidacao;
        }

        if (mensagemValidacao == '') {
            validacaoResult.flgError = false;
        } else {
            validacaoResult.flgError = true;
            alert(mensagemValidacao);
        } 
        return validacaoResult.flgError
    }