Problème de variables?

Pour toutes les discussions javascript, jQuery et autres frameworks
Répondre
BaptisteLer
Messages : 2
Enregistré le : 03 janv. 2021, 15:11

Problème de variables?

Message par BaptisteLer » 03 janv. 2021, 16:11

Bonjour à tous, d'abord bonne année !

Je suis en train de développer un petit site internet en HTML / CSS.
Je ne suis pas un développeur expert, il s'agit plutôt d'une passion, donc la question que je vais poser va peut-être sembler très basique :-)

Donc, utilisant du HTML/CSS, j'ai découvert le potentiel de JS. Maîtrisant peu ce langage, j'ai découvert également des ressources intéressantes sur ce site. J'ai analysé le code qui m’intéressait et j'ai pu intégrer l'effet "Futuristic resolving" à ma maquette pour un premier texte avec un effet typing qui me plait beaucoup (image1.PNG).

J'ai tenté de faire de même sur une autre rubrique (conçue sur le même modèle que image1.PNG) de la maquette mais ça ne fonctionne pas.

J'ai donc changé le nom des constantes et de variables parce que je me suis dit que si le deuxième script avait les mêmes variables que le premier script alors c'était normal qu'il y ait une confusion des deux scripts dans leur exécution. Pourtant ça ne fonctionne toujours pas.

Voici mon code html pour l'image 1 :

Code : Tout sélectionner

<div class="container">
  <h1 class="heading" data-target-resolver></h1>
</div>
<div id="carre2"></div>


Le code CSS correspondant :

Code : Tout sélectionner

.container {
  display: flex;
  
  height: 100%;
  padding: 6rem;
position : absolute;
margin-left : 33em;
margin-top : 10em;
z-index : 13;

}

.heading {
  color: #FFFFFF;
  font-size: 4rem;
  font-weight: 600;
  text-transform: uppercase;
position : absolute;
}
et le code javascript où est en rouge ce qui selon moi doit être modifié (en écrivant par exemple "data-target-resolver2"):

const resolver = {
resolve: function resolve(options, callback) {
// The string to resolve
const resolveString = options.resolveString || options.element.getAttribute('data-target-resolver');
const combinedOptions = Object.assign({}, options, {resolveString: resolveString});

function getRandomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};

function randomCharacter(characters) {
return characters[getRandomInteger(0, characters.length - 1)];
};

function doRandomiserEffect(options, callback) {
const characters = options.characters;
const timeout = options.timeout;
const element = options.element;
const partialString = options.partialString;

let iterations = options.iterations;

setTimeout(() => {
if (iterations >= 0) {
const nextOptions = Object.assign({}, options, {iterations: iterations - 1});

// Ensures partialString without the random character as the final state.
if (iterations === 0) {
element.textContent = partialString;
} else {
// Replaces the last character of partialString with a random character
element.textContent = partialString.substring(0, partialString.length - 1) + randomCharacter(characters);
}

doRandomiserEffect(nextOptions, callback)
} else if (typeof callback === "function") {
callback();
}
}, options.timeout);
};

function doResolverEffect(options, callback) {
const resolveString = options.resolveString;
const characters = options.characters;
const offset = options.offset;
const partialString = resolveString.substring(0, offset);
const combinedOptions = Object.assign({}, options, {partialString: partialString});

doRandomiserEffect(combinedOptions, () => {
const nextOptions = Object.assign({}, options, {offset: offset + 1});

if (offset <= resolveString.length) {
doResolverEffect(nextOptions, callback);
} else if (typeof callback === "function") {
callback();
}
});
};

doResolverEffect(combinedOptions, callback);
}
}

/* Some GLaDOS quotes from Portal 2 chapter 9: The Part Where He Kills You
* Source: http://theportalwiki.com/wiki/GLaDOS_vo ... _Kills_You
*/
const strings = [
'We strive for excellence and success',

'......'
];

let counter = 0;

const options = {
// Initial position
offset: 0,
// Timeout between each random character
timeout: 5,
// Number of random characters to show
iterations: 10,
// Random characters to pick from
characters: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'x', '#', '%', '&', '-', '+', '_', '?', '/', '\\', '='],
// String to resolve
resolveString: strings[counter],
// The element
element: document.querySelector('[data-target-resolver]')
}

// Callback function when resolve completes
function callback() {
setTimeout(() => {
counter ++;

if (counter >= strings.length) {
counter = 0;
}

let nextOptions = Object.assign({}, options, {resolveString: strings[counter]});
resolver.resolve(nextOptions, callback);
}, 1000);
}

resolver.resolve(options, callback);


Comme je l’écrivais, j'avais tenté de changer les variables du code javascript mais ça ne fonctionnait pas et c'était, je pense, une mauvaise approche. Je me dis qu'une solution pourrait être d'assigner l’exécution de ce script à la seule portion de html concernée par le script JS mais je ne sais pas si c'est faisable vu que quand j'ai changé data-target-resolver ça n'a eu absolument aucun effet. Quelqu'un aurait-il une piste?

Merci pour votre aide

Baptiste
Fichiers joints
image1.PNG
image1.PNG (132.75 Kio) Vu 2729 fois

Avatar du membre
webmaster
Administrateur du site
Messages : 563
Enregistré le : 28 févr. 2017, 15:19

Re: Problème de variables?

Message par webmaster » 04 janv. 2021, 10:52

Bonjour,

C'est toujours délicat de reprendre un code existant qui n'est pas documenté
Mais le paramètre data-target-resolver sert à identifier la balise concernée
Pour en gérer 2 en meme temps, il faut data-target-resolver et data-target-resolver2
et copier coller 2 fois la partie de code
const resolver = {...}
const resolver2 = {...}
en affectant data-target-resolver au 1er et data-target-resolver2 au 2eme

N'oubliez pas de regarder la console du navigateur pour identifier les erreurs :
https://www.toutjavascript.com/savoir/n ... script.php
TJS : 25 ans et mon livre Tout JavaScript chez Dunod
https://www.toutjavascript.com/livre/index.php

BaptisteLer
Messages : 2
Enregistré le : 03 janv. 2021, 15:11

Re: Problème de variables?

Message par BaptisteLer » 05 janv. 2021, 15:42

Bonjour, merci pour ce retour !

J'ai finalement réussi à trouver une solution qui semble fonctionner. Il y a un petit bug d'affichage lors de la première instance du second code (la phrase affichée dans la première image s'affiche 1 fois et n’apparaît plus ensuite).

Il y aura des travaux de finition à réaliser pour affiner le code mais dans la mesure où les utilisateurs prennent un certain temps à scroller jusqu'à la 2e image, ce n'est peut être pas gênant dans l'immédiat. après si quelqu'un a une solution en tête pour remédier à l'initialisation, je prends avec grand plaisir :-)

Voici le code :

Code : Tout sélectionner

const resolver = {
  resolve: function resolve(options, callback) {
    // The string to resolve
    const resolveString = options.resolveString || options.element.getAttribute('data-target-resolver');
    const combinedOptions = Object.assign({}, options, {resolveString: resolveString});
    
    function getRandomInteger(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    };
    
    function randomCharacter(characters) {
      return characters[getRandomInteger(0, characters.length - 1)];
    };
    
    function doRandomiserEffect(options, callback) {
      const characters = options.characters;
      const timeout = options.timeout;
      const element = options.element;
      const partialString = options.partialString;

      let iterations = options.iterations;

      setTimeout(() => {
        if (iterations >= 0) {
          const nextOptions = Object.assign({}, options, {iterations: iterations - 1});

          // Ensures partialString without the random character as the final state.
          if (iterations === 0) {
            element.textContent = partialString;
          } else {
            // Replaces the last character of partialString with a random character
            element.textContent = partialString.substring(0, partialString.length - 1) + randomCharacter(characters);
          }

          doRandomiserEffect(nextOptions, callback)
        } else if (typeof callback === "function") {
          callback(); 
        }
      }, options.timeout);
    };
    
    function doResolverEffect(options, callback) {
      const resolveString = options.resolveString;
      const characters = options.characters;
      const offset = options.offset;
      const partialString = resolveString.substring(0, offset);
      const combinedOptions = Object.assign({}, options, {partialString: partialString});

      doRandomiserEffect(combinedOptions, () => {
        const nextOptions = Object.assign({}, options, {offset: offset + 1});

        if (offset <= resolveString.length) {
          doResolverEffect(nextOptions, callback);
        } else if (typeof callback === "function") {
          callback();
        }
      });
    };

    doResolverEffect(combinedOptions, callback);
  } 
}

/* Some GLaDOS quotes from Portal 2 chapter 9: The Part Where He Kills You
 * Source: http://theportalwiki.com/wiki/GLaDOS_voice_lines#Chapter_9:_The_Part_Where_He_Kills_You
 */
const strings = [
  'We strive for excellence and success',
  
  '......'
];

let counter = 0;

const options = {
  // Initial position
  offset: 0,
  // Timeout between each random character
  timeout: 5,
  // Number of random characters to show
  iterations: 10,
  // Random characters to pick from
  characters: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'x', '#', '%', '&', '-', '+', '_', '?', '/', '\\', '='],
  // String to resolve
  resolveString: strings[counter],
  // The element
  element: document.querySelector('[data-target-resolver]')
}

// Callback function when resolve completes
function callback() {
  setTimeout(() => {
    counter ++;
    
    if (counter >= strings.length) {
      counter = 0;
    }
    
    let nextOptions = Object.assign({}, options, {resolveString: strings[counter]});
    resolver.resolve(nextOptions, callback);
  }, 1000);
}

resolver.resolve(options, callback);









const resolver2 = {
  resolve2: function resolve2(options2, callback2) {
    // The string to resolve
    const resolveString = options2.resolveString || options2.element2.getAttribute('data-target-resolver2');
    const combinedOptions = Object.assign({}, options2, {resolveString: resolveString});
    
    function getRandomInteger(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    };
    
    function randomCharacter(characters2) {
      return characters2[getRandomInteger(0, characters2.length - 1)];
    };
    
    function doRandomiserEffect(options2, callback2) {
      const characters2 = options2.characters2;
      const timeout = options2.timeout;
      const element2 = options2.element2;
      const partialString = options2.partialString;

      let iterations = options2.iterations;

      setTimeout(() => {
        if (iterations >= 0) {
          const nextOptions = Object.assign({}, options2, {iterations: iterations - 1});

          // Ensures partialString without the random character as the final state.
          if (iterations === 0) {
            element2.textContent = partialString;
          } else {
            // Replaces the last character of partialString with a random character
            element2.textContent = partialString.substring(0, partialString.length - 1) + randomCharacter(characters2);
          }

          doRandomiserEffect(nextOptions, callback2)
        } else if (typeof callback2 === "function") {
          callback2(); 
        }
      }, options2.timeout);
    };
    
    function doResolver2Effect2(options2, callback2) {
      const resolveString = options2.resolveString;
      const characters2 = options2.characters2;
      const offset = options2.offset;
      const partialString = resolveString.substring(0, offset);
      const combinedOptions = Object.assign({}, options2, {partialString: partialString});

      doRandomiserEffect(combinedOptions, () => {
        const nextOptions = Object.assign({}, options2, {offset: offset + 1});

        if (offset <= resolveString.length) {
          doResolver2Effect2(nextOptions, callback2);
        } else if (typeof callback2 === "function") {
          callback2();
        }
      });
    };

    doResolver2Effect2(combinedOptions, callback2);
  } 
}

/* Some GLaDOS quotes from Portal 2 chapter 9: The Part Where He Kills You
 * Source: http://theportalwiki.com/wiki/GLaDOS_voice_lines#Chapter_9:_The_Part_Where_He_Kills_You
 */
const strings2 = [
  'HOW CAN WE HELP?',
  'STRATEGIC DEPARTMENT',
  'ANALYSIS',
  'ESSENTIAL SERVICES',
  
  '......'
];

let counter2 = 0;

const options2 = {
  // Initial position
  offset: 0,
  // Timeout between each random character
  timeout: 5,
  // Number of random characters to show
  iterations: 10,
  // Random characters to pick from
  characters2: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'x', '#', '%', '&', '-', '+', '_', '?', '/', '\\', '='],
  // String to resolve
  resolveString: strings[counter2],
  // The element
  element2: document.querySelector('[data-target-resolver2]')
}

// Callback function when resolve completes
function callback2() {
  setTimeout(() => {
    counter2 ++;
    
    if (counter2 >= strings2.length) {
      counter2 = 0;
    }
    
    let nextOptions = Object.assign({}, options2, {resolveString: strings2[counter2]});
    resolver2.resolve2(nextOptions, callback2);
  }, 1000);
}

resolver2.resolve2(options2, callback2);
au plaisir d'échanger de nouveau avec vous et à bientôt

Répondre