javascript – ¿Cómo lanzar analytics con una función de js?

Debo lanzar el script de
Google Analytics desde una función de javascript.

Tengo el siguiente código

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-1234567-8"></script>
  <script>
    window.dataLayer = window.dataLayer || ();
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'UA-1234567-8', { 'anonymize_ip': true });
  </script>

¿Cómo puedo escribir el código dentro de una función?

Ya que tal cual o sin la etiqueta script no funciona.

Muchas gracias.

javascript – Find the odd int challange

this is a function given an array of numbers to find the one that appears an odd number of times.

what I did is:

  • Sort the array
  • Check if the array is odd.
  • If the array length is 1 then return this value.
  • Assign every two values to a new array, and check if it is a number.
  • Check if every two values are equals.
  • If not equals then the result will be the first element on the new array
function findOdd(A) {
  
  let copA = Array.from(A).sort((a, b) => a - b);
  let res = 0;

  if (copA.length % 2 === 0) return;
  if (copA.length == 1) return res = copA(0);
    
  let newArr = ();
  for (let i in copA) {
    // if not a integer break
    if (!Number.isInteger(copA(i))) {
      res = 0;
      break;
    };

    newArr.push(copA(i));
    if(newArr.length == 2) {
      const (a,b) = newArr;
      if (a === b) {
        newArr = ();
      } else {
        res = a;
        newArr(0) = b;
        break;
      }
    } else if (newArr.length == 1) {
        res = newArr(0);
    }
  }
  return res;
}

// test the code
findOdd((20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5)); // 5
findOdd((1,1,2,-2,5,2,4,4,-1,-2,5)); // -1
findOdd((20,1,1,2,2,3,3,5,5,4,20,4,5)); // 5
findOdd((10)); // 10
findOdd((1,1,1,1,1,1,10,1,1,1,1)); // 10
findOdd((5,4,3,2,1,5,4,3,2,10,10)); // 1

My code works well, but I looking to improve it.

javascript – Converter JSON em Array

Tenho o seguinte JSON:

let result = {"0":4,"10":4,"30":6,"60":9,"90":12,"120":15,"150":18,"180":21}

Preciso converter em Array no seguinte formato:

({"0":4},{"10":4},{"30":6},{"60":9},{"90":12},{"120":15},{"150":18},{"180":21})

Estou tentando da seguinte forma sem sucesso:

let dados = JSON.parse(result)

javascript – Retornar data JSON no HTML

Pessoa, preciso de ajuda com uma chamada de uma API, que retorna um JSON.

Já tentei diversas coisas, mas não consigo fazer com que retorne no meu HTML as informações.

Alguém consegue me apoiar com algum código? Não coloquei aqui o que usei pois utilizei vários.

inserir a descrição da imagem aqui

Só preciso pegar o name e o description. Já usei o name direto, usei values.name, mas nada funcionou.

Um exemplo do meu javascript

var pageCounter = 1;
var animalContainer = document.getElementById("animal-info");
var btn = document.getElementById("btn");

btn.addEventListener("click", function() {
  var ourRequest = new XMLHttpRequest();
  ourRequest.open('GET', '');
  ourRequest.onload = function() {
    if (ourRequest.status >= 200 && ourRequest.status < 400) {
      var ourData = JSON.parse(ourRequest.responseText);
      renderHTML(ourData);
    } else {
      console.log("We connected to the server, but it returned an error.");
    }    
  };
  ourRequest.onerror = function() {
    console.log("Connection error");
  };
  ourRequest.send();
  pageCounter++;
  if (pageCounter > 10) {
    btn.classList.add("hide-me");
  }
});
function renderHTML(data) {
  var htmlString = "";

  for (i = 0; i < data.length; i++) {
    htmlString += "<p>" + data.values(i).name + data.values(i).description;

    htmlString += '.</p>';

  }

  animalContainer.insertAdjacentHTML('beforeend', htmlString);
}
<header>
    <h1>JSON and AJAX</h1>
    <button id="btn">Fetch Info for 3 New Animals</button>
  </header>
  
  <div id="animal-info"></div>

  <script src="https://pt.stackoverflow.com/js/main.js"></script>

Obrigado.

javascript – problema al modificar variable global

en esta ocasión vengo por un error bastante simple que me ocurrió, pero que me ha dejado pensativo.
Sucede que tengo una variable normal declarada de forma global, obviamente fuera de la función, y la misma al darle cick a un elemento de mi menú, debe aumentar en 1 su valor. esto la verdad ya lo había hecho antes y la verdad no suponía un problema, pero al repetirlo con esta variable, simplemente no quiere funcionar

i2=0;
function buscar(){
    //buscador de texto
    //let texto=document.getElementById("texto1").value;
    // Obtener solo elementos en contenedor original
    //let texto2=b.getElementsByClassName(texto);

    //b.style.display="none";
    //bb.style.display="block";
    // Limpia el contenedor, no hay problema
    //bb.innerHTML="";

 i2=i2+1; //ya intenté con i2++, i2=+1;
 
    // Limitas el for con la cantidad de elementos obtenidos
    //for(let num=0; num<texto2.length; num++){
        // Inserta una copia, en lugar del original
        //bb.appendChild(texto2(num).cloneNode(true));
    }
 
}

if(i2<0){

  c.style.display="none"; //i2 se queda en 0 y sigue ejecutando esta parte
}

Ahora, apliqué eso mismo con el siguiente código y funciona:

i=0;
function menu2 (){
 //infoc.style.display="none";
  //c.style.display="inherit";
   //a2.style.display="none"; 

 i=i+1;
}

 if(i==1){
    //a2.style.display="none";
     //b.setAttribute("style","margin-top:10px;"); //este si funciona
  }

la verdad es algo muy básico pero es que no encuentro diferencia alguna entre ambos códigos; he modificado variables de esta forma antes y ya intentado devolviendo su valor, cambiando el nombre, los símbolos de (<>) por (==, =) y nada. Cabe destacar, todo lo demás, funciones… funciona perfectamente
Muchas gracias por todo

javascript – Como acessar uma função de um componente no onMouseEnter de outro componente – ReactJS

Criei um componente de um cursor personalizado, e tenho uma função nele que altera o tamanho do mesmo.

Queria que, quando o mouse ficasse em cima de outro componente (que no meu caso é um botão), executasse essa tal função de alterar o tamanho do cursor.

<ButtonStyled onMouseEnter={ alterarTamanhoDoCursor }>
    {this.props.text}
</ButtonStyled>

javascript – Tracking Ad revenue per page?

I’m trying to look for an ad service that allows me to track revenue per page.

Say a user creates content, a page. The page has an id of 5. On this page, one or more ads are displayed. However, a feature of my website allows users to get a compensation of the ad revenue for creating content (a post).

Are there any web ad services that allow you to track how much revenue is generated on specific page URLs? Or even, a page where I can place some kind of tracking ID in the ad code which I can then reference in my database later?

Example:

<!-- A typical post page made by a user -->
<?php $postID = get_post_id();?>
<script src="https://adservice.com/?myadid=19028?postID=<?php echo $postID ?>>
...
</script>

<!-- Example Backend to retrieve advertisement stats from a post ID and display it -->
<?php
    $postID = 200;
    $adStats = get_ad_stats($postID);
    
    echo $adStats("revenue") . " ";
    echo $adStats("clicks") . " ";
    echo $adStats("impressions") . " ";
?>

I’m not sure if Google Adsense allows this. Also at the time of writing, their API/documentation appears to be down. Is there any advertising rest API service that allows this?

javascript – Is it possible to programmatically purchase something through a Google Chrome Addon?

I’m new to writing Google Chrome Addons so hopefully the answer to this question is not super obvious.

Is it possible to write a Google Chrome Addon that purchases an item for a user? For example, it would log into the user’s online account, add an item to cart and complete purchase? I’m thinking along the lines of Selenium WebDriver but as a standalone, self executing Chrome Extension.

Obviously, it would be done only with a user’s permission. My question is: does the Chrome Addon tech allows for this possibility? If so, which functions should I be focusing on to start?

Thanks

How to save the data of an array by prompts and bond with a class in javascript

I am learning poo in javascript for the first time and I am making a program in which by means of prompts the data is stored in an array and then linking that data with a class and being displayed in a message, but I don’t know how to do that the data in the array is bound to the class. If someone could help me with a very basic solution since I don’t know much so far, thank you.

class Libro {

   constructor(titulo, autor, año, genero) {

      this.titulo = titulo
      this.Autor = autor
      this.Año = año
      this.Genero = genero
   }

   informacion() {
      return console.log(`El libro ${this.titulo} del autor ${this.Autor} fue publicado en el año ${this.Año} y es de genero ${this.Genero}`);
   }
}

let titulo1 = prompt('Introduce el titulo del libro')
let autor1 = prompt('Introduce el autor del libro')
let año1 = prompt('Introduce el año en que fue publicado el libro')
let genero1 = prompt('Introduce el genero literario del libro')

let libro1 = (titulo1, autor1, año1, genero1);

libro1.push(new Libro(titulo, autor, año, genero))

console.log(libro1.Libro());

javascript – Layout was forced before the page was fully loaded

I’m testing a Drupal 9 site and it is loading oddly. In development mode in the browser I see the message

“Layout was forced before the page was fully loaded. If stylesheets
are not yet loaded this may cause a flash of unstyled content.
modernizr.min.js:3:6185”

Does anyone know how I get round this? I’m not a developer and am creating this site for a charity, that’s why I have to ask for help.