How do I get the correct width of an element in all broswers in JavaScript?

I am trying to get the width of an element to be able to set width of another element EXACTLY as big as the first one. The problem I am facing is that different broswers seem to give me different results, no matter the method I am using.

Basically I have an input field which I want to set to the size of the selected option. I use the following JS which fundamentally works fine:

var inputFields = document.querySelectorAll(".my-input-field");

// Resize on change
inputFields.forEach(function(element) {
    element.addEventListener("change", function() {
        resizeSelect(element);
    });
});

function resizeSelect(sel) {
    let tempOption = document.createElement('option');
    tempOption.textContent = sel.options[sel.selectedIndex].textContent;

    let tempSelect = document.createElement('select');
    tempSelect.style.visibility = "hidden";
    tempSelect.style.position = "fixed"
    tempSelect.appendChild(tempOption);

    sel.after(tempSelect);
    sel.style.width = (parseInt(window.getComputedStyle(tempSelect).width) - 25) + 'px';
    tempSelect.remove();

}

In this case I use window.getComputedStyle(tempSelect).width to get the width which gives me 201px in Firefox and 196px in Edge (I haven’t tried more browsers yet). Where is this difference coming from?

I also tried to use tempSelect.offsetWidth and tempSelect.getBoundingClientRect()['width] with the same result.

Is there a browser independent solution that gives me the exact width of an element?

Validating input fields form vue

**I wonder how can I run the emit in the App.vue file if all of the input fields of a multistep form are filled? I’ve written the logic but I can’t get the final block displayed in the end when all of the fields are filled.

https://codesandbox.io/s/intelligent-jasper-teh1im?file=/src/components/Button.vue

<template>
  <button class="btn" @click="submit">Submit</button>
</template>

<script>
export default {
  methods: {
    submit() {
      if (
        this.firstName !== "" &&
        this.lastName !== "" &&
        this.paymentAmount !== "" &&
        this.accountNumber !== ""
      ) {
        this.$emit("final");
      } else {
        alert("please fill the required fields");
      }
    },
  },
};
</script>

<style scoped>
.btn {
  padding: 10px 30px;
}
</style>

**

WebGL video, where pixels with zero alpha are discarded?

I load a video to webGL:

  gl.bindTexture(gl.TEXTURE_2D, texture);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, video);

The video has a part with alpha=0.0 but rgb != 0.0 (for next blending).
Inside the shader I see rgb = 0.0.
Where were the colors discarded and who did it?

video in format .webm with codec VP8.

What approach should I take with dropdowns and select all option

I have multi-select dropdown with 3000 tasks loaded from a database. Many tasks can be assigned to a user and I want to have the option ‘Select all’, but the front end is the easy part.

My Laravel database structure is the following:
I have a table with all of the tasks and a table named user_has_task where I insert every assigned task of the user. Then I use global scopes to filter the tasks accessible by the user.

But the question is what approach should I use – I can insert all 3000 tasks as new records in the user_has_task (imagine having 100 users who all have access to every task, the table will become very big 100*3000 = 300000 records) or I could insert some specific single record that tells the code that this user has access to every task (but this way I will lose the ability to remove specific assigned tasks from the user (imagine assigning 3000 tasks but you want to removed 1 of the tasks from this user))

Listening to an opened WebSocket and fetching incoming messages on the browser-side

I’m struggling with something about WebSockets and I can’t figure out why.

A bit more context

On this page, there is a Web Socket that is called “notify.bubble.is” that is provided by Bubble, a no-code tool that allows you to build web applications without code.

Existing Web Socket

I’d like to listen to the messages coming from the server (and especially one that is “has-last-change-flusk-privacy…”) and intercept them.

The problem

I tried several things in order to listen to this WebSocket :

  • Writing function ‘onmessage’ on the window.WebSocket object to log the message into the console (did not work)
  • Creating a new WebSocket and connect it to the same address as the existing one (wss://notify.bubble.is) but it receives no messages
  • Overriding prototype of window.WebSocket object to rewriting the ‘onmessage’ function (did also not work)
  • Adding an EventListener to the document with event ‘onmessage’ but it receives no messages

So I’m a bit confused…
I’m 99% sure there is a way to fetch these messages, and I think you guys could have wonderful and maybe out-of-the-box ideas (or maybe it’s very easy and I’m just so bad)!

If you need more details, more info, or anything… just ask and I’ll answer as soon as I can.
Thanks, guys! 🙂

How to use v-data-table with v-if to render automatically?

I’m trying to use v-data-table with data filter but it’s not allowing my attempt below,

   <v-data-table :headers="colunas" :items="form.itens" :items-per-page="15" class="elevation-1">
            <template v-if="!item.excluido" v-slot:item="{ item }">
              <template v-slot:item.menu="{ item, index }">
                <v-icon left @click="delItem(item, 'or')" color="red">fa fa-trash-alt</v-icon>
                <v-icon right @click="edtItem(item, index)" color="orange">fa fa-pencil</v-icon>
              </template>
              <template v-slot:item.custo="{ item }">
                <span class="text-green"
                  ><v-icon small color="green" left>fa-solid fa-brazilian-real-sign</v-icon></span
                >
                <span class="text-bold">{{ formVlr(item.custo) }}</span>
              </template>
              <template v-slot:item.tt_custo="{ item }">
                <span class="text-green"
                  ><v-icon small color="green" left>fa-solid fa-brazilian-real-sign</v-icon></span
                >
                <span class="text-bold">{{ formVlr(item.tt_custo) }}</span>
            </template>
          </v-data-table>

icon is not working in react native paper text input

Code

                     <TextInput
                            mode="outlined"
                            label="Enter Password"
                            outlineColor="#000"
                            activeOutlineColor="#0073D9"
                            right={<TextInput.Icon name="eye" />}
                            style={{
                                backgroundColor: '#eee', marginRight: scale(20),
                                marginLeft: scale(20),
                            }}
                            value={Pass}
                            onChangeText={(text) => setPass(text)}
                        />

Output

enter image description here

How to add an icon in react native paper text input?

Bootstrap 5 – Carousel is not working correctly please suggest me some reason [closed]

https://test.opendata-oepnv.de/ht/de/willkommen
the carousel is not working as expected hier please can someone tell me some reason can cause this issue
i checked the bootstrap classes and they are all up to date

https://test.opendata-oepnv.de/ht/de/willkommen
the carousel is not working as expected hier please can someone tell me some reason can cause this issue
i checked the bootstrap classes and they are all up to date

How I can change object by Id in nested array with childrens, and update state in React

How can i toggle isExpanded property on onClick by Id. I’m using React for this project.
Here is my json data structure.

const handleExpandOutlineItem = (id: string) => {}

here is my json data structure.

  {
    id: '1',
    title: 'Introduction to Programming',
    isExpanded: true,
    children: [
      {
        id: '1.1',
        title: 'What is programming?',
        isExpanded: false,
        children: [
          {
            id: '1.1.1',
            title: 'What is programming?',
            isExpanded: false,
            children: [],
          },
          {
            id: '1.1.2',
            title: 'What is programming?',
            isExpanded: false,
            children: [],
          },
        ],
      },
      {
        id: '1.2',
        title: 'Programming languages',
        isExpanded: false,
        children: [
          {
            id: '1.2.1',
            title: 'Programming languages',
            isExpanded: false,
            children: [],
          },
          {
            id: '1.2.2',
            title: 'Programming languages',
            isExpanded: false,
            children: [],
          },
        ],
      },
    ],
  },
]```

I trie to use recursion, but I should also update state

How to mock module which got through webpack

I am trying to mock module using JASMINE in angular but we are unable to mock it.

Below is code we are using use the module in MainComponent.ts

“””
const authAppService = () => import(“authApp/auth”).then((m) => m.authService);const storeAppService = () => import(“storeApp/store”).then((m) => m.storeService);
“””

“””
import * as authAppService from ‘authApp/auth’;

beforeAll(() => {    mockParseString = spyOn(authAppService, ‘isAuthenticated’).and.callThrough();  });

“””

Getting the error ” Error: Module not found: Error: Can’t resolve ‘authApp/auth’ ” 

When the unit test cases are executed using the command “npm test”

ProseMirror: How to add an attribute to pasted content?

I want to add an attribute which will be rendered as an HTML attribute to content that was pasted.

I have been trying to implement this using something like the following function:

transformPasted: (slice) => {
    let fragment = slice.content
    fragment.forEach((node, _, index) => {
        fragment = fragment.replaceChild(
            index,
            schema.node(
                node.type,
                {
                    ...node.attrs,
                    pasted: true,
                },
                node.content,
                node.marks,
            ),
        )
    })
    return new Slice(fragment, slice.openStart, slice.openEnd)
},

This does seem to be setting the attribute correctly however it still always displays pasted="false" in the HTML. I haven’t managed to successfully change the HTML attribute to pasted="true".

Any guidance would be appreciated.

window onload not invoking when the page gets loaded [closed]

Not seeing al alert of “let’s go!”

<html>

<head>
  <script type="text/javascript">
    function simple() {
      alert("let's go!");
    }
    window.onload = simple;
    async function getPlatforms() {
      alert "hello"
      const response = await fetch(
        'http://10.64.127.94:5000/api/get_platforms', {
          method: 'GET',
        }
      );
      const data = await response.json();
      alert data
    }

    function selects() {
      var ele = document.getElementsByName('chk');
      for (var i = 0; i < ele.length; i++) {
        if (ele[i].type == 'checkbox')
          ele[i].checked = true;
      }
    }

    function deSelect() {
      var ele = document.getElementsByName('chk');
      for (var i = 0; i < ele.length; i++) {
        if (ele[i].type == 'checkbox')
          ele[i].checked = false;
      }
    }
    <!--        function SubmitForm(formId) {-->
    <!--            var oForm = document.getElementById(formId);-->
    <!--            if (oForm) {-->
    <!--                oForm.submit();-->
    <!--            }-->
    <!--            else {-->
    <!--                alert("DEBUG - could not find element " + formId);-->
    <!--            }-->
    <!--        }-->
  </script>
  <style>
    table,
    th,
    td {
      border: 1px solid black;
      border-collapse: collapse;
    }
  </style>
  <title>Unified Performance Heat Map</title>
</head>

<body>
  <h1 style="text-align: center;">Unified Performance Heat Map</h1>
  <hr>
  <form name="device_form" id="device_form">
    <label>Choose a device:</label>
    <select name="device_select" id="device_select">
    </select>
  </form>
  <br>
  <br>
  <label>Select the label:</label>
  <select name="label_select" id="label_select">
  </select>
  <br>
  <br>
  <label>Select the baseline:</label>
  <select name="label_baseline" id="label_baseline">
  </select>
  <br>
  <br>
  <label>Select the features:</label>
  <br>

  <br>
  <input type="button" onclick='selects()' value="Select All" />
  <input type="button" onclick='deSelect()' value="Deselect All" />

  <br>
  <br>
  <button type="button">Make Heat Map !</button>
  <hr>
  <table style="width:100%">
    <tr>
      <td>FEATURE</td>
      <td colspan="3" style="text-align: center;">IPSEC</td>
    </tr>
    <tr>
      <td>PACKET</td>
      <td>64</td>
      <td>IMIX</td>
      <td>1400</td>
    </tr>
    <tr>
      <td>BASE</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td>LABEL</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td>HEATMAP</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </table>
</body>

</html>

Can’t select language code in web-scraping script (RSelenium, Chrome)

First of all it’s important to know that I received the script I will be talking about, I did not create it myself. In fact, I am very new to R and don’t have any programming background at all. So very simple explanations or direct changes would be extremely appreciated, thank you in advance for your patience!

The script allows you to scrape Goodreads-reviews with RSelenium. I run in in Rstudio on a Windows-computer (not sure whether this is relevant or not). You put in the url of the book in question, the script then opens the Chrome-browser and navigates the url. The script will then scrape the 300 reviews shown. However, Goodreads allows you to filter the reviews per language. The script has a piece of code so you can select which language you want (e.g. only English reviews). For this, you can either enter the language code (‘en’ for English) or the the number of the position of this language in the drop-down menu. This position of the language varies from book to book, as the languages are ordered alphabetically and different books may have reviews in different languages.

My problem is: the language code part of the selector does not work, it only accepts the numeral order. However, it’s very tiring to have to look up the position of a specific language for every single book and to then fill it in. I just want to be able to give in the language code.

This is the full script (just set the output-directory at the end if you wish to run it):

library(rJava)        # Required to use RSelenium
library(data.table)   # Required for rbindlist
library(dplyr)        # Required to use the pipes %>% and some table manipulation commands
library(magrittr)     # Required to use the pipes %>%
library(rvest)        # Required for read_html
library(RSelenium)    # Required for webscraping with javascript
library(lubridate)    # Required to scrape the correct dates
library(stringr)      # Required to cut off any leading or trailing whitespace from text
library(purrr)


options(stringsAsFactors = F) #needed to prevent errors when merging data frames

#Paste the GoodReads Url
url <- "https://www.goodreads.com/book/show/96290.Die_unendliche_Geschichte"

englishOnly = F #If FALSE, all languages are chosen

#Set your browser settings (if chrome not working, pick closest version)
rD <- rsDriver(port = 9516L, browser = "chrome", chromever = "110.0.5481.30")
remDr <- rD[["client"]]
remDr$setTimeout(type = "implicit", 2000)
remDr$navigate(url)

bookTitle = unlist(remDr$getTitle())
finalData = data.frame()

# Main loop going through the website pages
morePages = T
pageNumber =  1
while(morePages){
  
  #Select reviews in correct language
  #Go to the goodreads page of the book in Chrome and right-click.
  #Click on "View Page Source".
  #Look for the language code, it will look like this:
  #<select name="language_code" id="language_code"><option value="">All Languages</option><option value="de">Deutsch &lrm;(9)</option>
  #<option value="en">English &lrm;(9)</option><option value="es">Español &lrm;(1)</option>
  #The numeral language code is the sequence, so here "All Languages" is 1, "Deutsch" is 2, "English" is 3...
  #This sequence is not the same for every book, so check it each time!
  #It is sufficient if you only fill in the numeral language code.
  selectLanguage = if(englishOnly){
    selectLanguage = remDr$findElement("xpath", "//select[@id='language_code']/option[@value='de']")
  } else {
    selectLanguage = remDr$findElement("xpath", "//select[@id='language_code']/option[4]")
  }
  
  selectLanguage$clickElement()
  Sys.sleep(1)
  
  #Expand all reviews
  expandMore <- remDr$findElements("link text", "...more")
  expandMore = sapply(expandMore, function(x) x$clickElement())
  
  #Extracting the reviews from the page
  reviews <- remDr$findElements("css selector", "#bookReviews .stacked")
  reviews.html <- lapply(reviews, function(x){x$getElementAttribute("outerHTML")[[1]]})
  
  #Remove double text when expanded
  reviews.html <- lapply(reviews.html, function(x){
    if(str_count(x, "span id="freeText") > 1) {
      str_remove(x, "<span id="freeTextContainer.*")
    } else {
      x
    }
  })
  
  reviews.list <- lapply(reviews.html, function(x){read_html(x) %>% html_text()} )
  reviews.text <- unlist(reviews.list)
  
  #Some reviews have only rating and no text, so we process them separately
  onlyRating = unlist(map(1:length(reviews.text), function(i) str_detect(reviews.text[i], "^\n\n")))
  
  #Full reviews
  if(sum(!onlyRating) > 0){
    
    filterData = reviews.text[!onlyRating]
    fullReviews = purrr::map_df(seq(1, length(filterData), by=2), function(i){
      review = unlist(strsplit(filterData[i], "n"))
      
      data.frame(
        date = mdy(review[2]), #date
        username = str_trim(review[5]), #user
        rating = str_trim(review[9]), #overall
        comment = str_trim(review[12]) #comment
      )
    })
    
    #Add review text to full reviews
    fullReviews$review = unlist(purrr::map(seq(2, length(filterData), by=2), function(i){
      str_trim(str_remove(filterData[i], "\s*\n\s*\(less\)"))
    }))
    
  } else {
    fullReviews = data.frame()
  }
  
  #partial reviews (only rating)
  if(sum(onlyRating) > 0){
    
    filterData = reviews.text[onlyRating]
    partialReviews = purrr::map_df(1:length(filterData), function(i){
      review = unlist(strsplit(filterData[i], "n"))
      
      data.frame(
        date = mdy(review[9]), #date
        username = str_trim(review[4]), #user
        rating = str_trim(review[8]), #overall
        comment = "",
        review = ""
      )
    })
    
  } else {
    partialReviews = data.frame()
  }
  
  #Get the review ID's from all the links
  reviewId = reviews.html %>% str_extract("/review/show/\d+")
  partialId = reviewId[(length(reviewId) - nrow(partialReviews) + 1):length(reviewId)] %>% 
    str_extract("\d+")
  if(nrow(fullReviews) > 0){
    reviewId = reviewId[1:(length(reviewId) - nrow(partialReviews))]
    reviewId = reviewId[seq(1, length(reviewId), 2)] %>% str_extract("\d+")
  } else {
    reviewId = NULL
  }
  
  if(nrow(partialReviews) > 0){
    reviewId = c(reviewId, partialId)
  }
  
  finalData = rbind(finalData, cbind(reviewId, rbind(fullReviews, partialReviews)))
  
  #Go to next page if possible
  nextPage = remDr$findElements("xpath", "//a[@class='next_page']")
  if(length(nextPage) > 0){
    message(paste("PAGE", pageNumber, "Processed - Going to next"))
    nextPage[[1]]$clickElement()
    pageNumber = pageNumber + 1
    Sys.sleep(2)
  } else {
    message(paste("PAGE", pageNumber, "Processed - Last page"))
    morePages = FALSE
  }
  
}   
#end of the main loop

#Replace missing ratings by 'not rated'
finalData$rating = ifelse(finalData$rating == "", "not rated", finalData$rating)

#Stop server
remDr$close()
rD$server$stop()
rm(rD, remDr)
gc()
system("taskkill /im java.exe /f", intern=FALSE, ignore.stdout=FALSE)

#set directory to where you wish the file to go
#copy your working directory and exchange all backward slashes for forward slashes
getwd()
setwd("")

#Write results
write.csv(finalData, paste0(bookTitle, ".csv"), row.names = F)
message("FINISHED!")

The part I’m talking about is this:

  selectLanguage = if(englishOnly){
    selectLanguage = remDr$findElement("xpath", "//select[@id='language_code']/option[@value='de']")
  } else {
    selectLanguage = remDr$findElement("xpath", "//select[@id='language_code']/option[4]")
  }
  
  selectLanguage$clickElement()
  Sys.sleep(1)

In this case, it only seems to take the “4” into consideration and will completely ignore the “de”. I don’t really need the numeral version, I just want to be able to enter the language code and get going. Would someone be willing to help me?

Because of my lack of experience, I first tried to use chatGPT to come up with a solution, but that went about as well as you’d expect.

I have two buttons in a row, both containing icons, but if one of the icons is larger, the other button gets pushed down despite same height. Why?

I am using Web Components on Stencil.js. I have an icon component, and a button component. I have nested the icon component inside the button component, but I have noticed that, when I have two buttons aligned next to each other, and one of them has an icon a bit larger than the other one, the other button gets pushed down. This is to be expected if the line-height is larger, but in my case, I don’t think that it is.

Button:

<button >
   {this.icon && this.position === 'left' && <ifx-icon icon={this.icon}></ifx-icon>}
   <slot></slot>
   {this.icon && this.position === 'right' && <ifx-icon icon={this.icon}></ifx-icon>}
</button>

Relevant button css:

.btn {
  display: inline-flex; 
  align-items: center;
  min-width: 80px;
  min-height: 40px;
  padding: 0px 16px;
  gap: 8px;
  color: #FFFFFF;
  flex-direction: row;
  font-weight: 600;
  border-radius: 1px;
  line-height: 24px;
  outline: none;
  font-family: tokens.$font-family-body;
  text-decoration: none;
  user-select: none;
  border: 1px solid rgba(0, 0, 0, 0);
  font-size: 1rem;
  transition: color .15s ease-in-out, background-color .15s ease-in-out, border-color .15s ease-in-out, box-shadow .15s ease-in-out;
}

Icon component:

 <Host>
    {this.constructIcon()}
 </Host>

Icon component CSS:

ifx-icon { 
  display: inline-flex;
}

HTML:
my button
my button

Result:
Buttons

If both icons are bell-16, both buttons are perfectly alined.
If I removed the inline-flex from the icon component, I get this:
No flex

..obviously because the icon is not aligned in the center inside the icon component, and has larger line-height than the text.
buttons2

Question: What pushes the left button down when the right one has a larger icon? Is it the line-height of the icon svg? If so, can it be prevented?