Ako upraviť hodnotu časovača JavaScript pre hru na písanie pomocou tlačidiel HTML

Ako upraviť hodnotu časovača JavaScript pre hru na písanie pomocou tlačidiel HTML
Ako upraviť hodnotu časovača JavaScript pre hru na písanie pomocou tlačidiel HTML

Dynamické nastavenie časovača pre písanie hier pomocou tlačidiel

V hre na písanie je ovládanie tempa hry rozhodujúce pre zaistenie pútavého používateľského zážitku. Jedným z dôležitých faktorov je časovač, ktorý určuje, ako dlho musí používateľ dokončiť hru alebo výzvu na písanie. Umožnením používateľom upraviť časovač hry pomocou jednoduchých tlačidiel HTML im môžete poskytnúť väčšiu kontrolu nad hrou.

Tento článok vám ukáže, ako vytvoriť riešenie v JavaScripte, ktoré umožňuje hráčom vybrať si medzi rôznymi nastaveniami časovača pomocou tlačidiel. Napríklad výber tlačidla „30s“ upraví časovač na 30 sekúnd, zatiaľ čo kliknutím na tlačidlo „60s“ ho zmeníte na 60 sekúnd.

Funkcia JavaScript prevezme hodnotu z kliknutého tlačidla a dynamicky aktualizuje časovač aj názov hry. Tento druh flexibility môže zlepšiť používateľský zážitok, vďaka čomu je hra prispôsobiteľnejšia a zábavnejšia pre rôzne úrovne zručností.

Na konci tejto príručky budete mať plne funkčnú funkciu úpravy časovača pomocou HTML a JavaScriptu. Popíšeme tiež, ako aktualizovať zobrazenú hodnotu časovača v názve stránky, aby odrážala zvolené trvanie časovača.

Príkaz Príklad použitia
document.querySelector() Používa sa na výber prvku HTML na dynamickú aktualizáciu názvu karty prehliadača. Táto metóda je špecifická pre výber prvkov na základe ich selektora CSS a tu pomáha zmeniť názov stránky na základe vybratej hodnoty časovača.</td> </tr> <tr> <td>addEventListener()</td> <td>Spája konkrétnu udalosť (napr. kliknutie) s prvkom tlačidla. V tomto kontexte sa používa na spustenie funkcie changeTimer(), keď používateľ klikne na tlačidlo, čo umožňuje dynamickú interakciu s nastaveniami časovača.</td> </tr> <tr> <td>innerText</td> <td>Táto vlastnosť umožňuje úpravu viditeľného textu v prvku HTML. V tomto riešení sa používa na aktualizáciu hodnoty časovača v názve stránky po kliknutí na tlačidlo.</td> </tr> <tr> <td>onClick</td> <td>Atribút obsluhy udalosti v riadku používaný v alternatívnom prístupe na pripojenie funkcie changeTimer() priamo k udalosti kliknutia tlačidla. To umožňuje jednoduchší, menej modulárny spôsob dynamickej aktualizácie časovača.</td> </tr> <tr> <td>test()</td> <td>Táto metóda sa používa pri testovaní jednotiek s Jest. Definuje testovací prípad, v ktorom sa testovaná funkcia (napr. changeTimer()) vyhodnotí, aby sa zabezpečila správna aktualizácia časovača. Zabezpečuje, aby sa kód choval podľa očakávania v rôznych scenároch.</td> </tr> <tr> <td>expect()</td> <td>Príkaz Jest, ktorý kontroluje, či sa skutočná hodnota (ako aktualizovaný časovač) zhoduje s očakávanou hodnotou. Používa sa v jednotkových testoch na overenie, že gameTime a document.title sú správne aktualizované po kliknutí na tlačidlo.</td> </tr> <tr> <td>toBe()</td> <td>Ďalší príkaz Jest, ktorý kontroluje prísnu rovnosť. Zabezpečuje, že po zavolaní changeTimer() je herný čas presne taký, ako sa očakáva (napr. 30 000 ms počas 30 sekúnd).</td> </tr> <tr> <td>getElementById()</td> <td>Používa sa na výber konkrétnych tlačidiel podľa ich ID (napr. „tridsať“, „šesťdesiat“). Táto metóda je dôležitá pre pripojenie poslucháčov udalostí k tlačidlám a spúšťanie dynamickej zmeny časovača v reakcii na interakciu používateľa.</td> </tr></table><h3 id="dev1">Vytváranie dynamických časovačov pomocou JavaScriptu a tlačidiel HTML</h3><div class="bordersh3"></div><p>Vyššie poskytnuté skripty sú navrhnuté tak, aby umožnili používateľovi dynamicky upravovať časovač hry v hre na písanie kliknutím na tlačidlá HTML. Na začiatku deklarujeme premennú <b>herný čas</b>, ktorá obsahuje čas v milisekundách (štandardne 30 sekúnd, vynásobením 1 000 sa prevedie na milisekundy). Kľúčová funkcia spočíva v <b>changeTimer</b> funkcia, ktorá aktualizuje hodnotu časovača na základe kliknutia na tlačidlo. Táto metóda získa hodnotu tlačidla (napr. 30, 60 alebo 90) a aktualizuje herný čas podľa toho variabilné. Skript navyše aktualizuje názov stránky tak, aby odrážal zvolené trvanie časovača, aby bolo používateľom jasné, koľko času majú.</p><p>Pre dynamické správanie využívame poslucháčov udalostí, konkrétne <b>addEventListener</b> príkaz. To umožňuje skriptu reagovať, keď používateľ klikne na niektoré z tlačidiel. Každému tlačidlu je priradené ID a po kliknutí sa spustí <b>changeTimer</b> funkciu, prejdením príslušnej časovej hodnoty. Tento prístup je užitočný na efektívne spracovanie viacerých tlačidiel bez potreby opakovaného vloženého JavaScriptu v štruktúre HTML. Skript obsahuje aj záložnú možnosť, kde môžete použiť inline obslužné nástroje udalostí, ako napr <b>onClick</b> ak sa uprednostňuje jednoduchosť pred modularitou.</p><p>V alternatívnom riešení priamo viažeme <b>onClick</b> udalosť na tlačidlá. Táto metóda vykonáva <b>changeTimer</b> fungovať priamo po kliknutí na tlačidlo. Je to priamy prístup, ale chýba mu flexibilita metódy poslucháča udalostí. Jednoduchosť tejto metódy je užitočná pre menšie, menej zložité aplikácie. Pre škálovateľnejší kód však poslucháči udalostí ponúkajú väčšiu flexibilitu a umožňujú jednoduchšie aktualizácie skriptu bez priamej úpravy štruktúry HTML. Obe metódy majú za cieľ vyriešiť rovnaký problém, ktorým je nastavenie časovača a dynamická aktualizácia titulu na základe výberu používateľa.</p><p>Nakoniec implementujeme unit testy pomocou Jest, testovacieho rámca JavaScriptu. The <b>test</b> funkcie sú kľúčové na overenie správnosti aktualizácie časovača. Testovaním viacerých scenárov, napríklad či sa časovač upraví na 30 sekúnd, 60 sekúnd alebo 90 sekúnd, tieto testy jednotiek zaisťujú správnosť skriptu. Príkazy ako <b>očakávať</b> a <b>toBe</b> sa používajú na overenie, či skutočná hodnota časovača a názov stránky zodpovedajú očakávaným výsledkom. Táto testovacia fáza zaisťuje, že vaša logika časovača funguje správne v rôznych prípadoch použitia a poskytuje dôveru v robustnosť vášho riešenia.<div id="script0"><h3>Zmena hodnoty časovača pomocou tlačidiel HTML pre hru na písanie</h3><div class="bordersh3"></div><p class="langprog">Vstupný prístup založený na JavaScripte s dynamickou aktualizáciou času a úpravou názvu</p><pre class="language-javascript"><code>// Solution 1: Using event listeners to change timer value dynamically</code> <code>let gameTime = 30 * 1000; // Default timer set to 30 seconds</code> <code>const titleElement = document.querySelector('title');</code> <code>function changeTimer(value) {</code> <code> gameTime = value * 1000; // Update timer to selected value</code> <code> titleElement.innerText = value + 's'; // Update the title</code> <code>}</code> <code>// Attach event listeners to buttons</code> <code>document.getElementById('thirty').addEventListener('click', () => changeTimer(30));</code> <code>document.getElementById('sixty').addEventListener('click', () => changeTimer(60));</code> <code>document.getElementById('ninety').addEventListener('click', () => changeTimer(90));</code> <code>// HTML Buttons:</code> <code>// <button id="thirty" type="button">30s</button></code> <code>// <button id="sixty" type="button">60s</button></code> <code>// <button id="ninety" type="button">90s</button></code> </pre></div><div id="script1"><h3>Alternatívny prístup: Používanie funkcií Inline HTML a JavaScript</h3><div class="bordersh3"></div><p class="langprog">Vložený JavaScript v HTML s priamym volaním funkcií po kliknutí na tlačidlo</p><pre class="language-javascript"><code><script></code> <code>let gameTime = 30 * 1000;</code> <code>function changeTimer(value) {</code> <code> gameTime = value * 1000;</code> <code> document.title = value + 's';</code> <code>}</code> <code></script></code> <code><button onClick="changeTimer(30)">30s</button></code> <code><button onClick="changeTimer(60)">60s</button></code> <code><button onClick="changeTimer(90)">90s</button></code> </pre></div><div id="script2"><h3>Testovanie jednotiek na zmeny hodnoty časovača v rôznych prostrediach</h3><div class="bordersh3"></div><p class="langprog">Unit testy založené na JavaScripte s použitím Jest na overenie front-end prostredia</p><pre class="language-javascript"><code>// Jest Test Cases</code> <code>test('Timer should update to 30 seconds', () => {</code> <code> changeTimer(30);</code> <code> expect(gameTime).toBe(30000);</code> <code> expect(document.title).toBe('30s');</code> <code>});</code> <code>test('Timer should update to 60 seconds', () => {</code> <code> changeTimer(60);</code> <code> expect(gameTime).toBe(60000);</code> <code> expect(document.title).toBe('60s');</code> <code>});</code> <code>test('Timer should update to 90 seconds', () => {</code> <code> changeTimer(90);</code> <code> expect(gameTime).toBe(90000);</code> <code> expect(document.title).toBe('90s');</code> <code>});</code> </pre></div></p><h3>Zlepšenie interakcie s hrou pomocou prispôsobenia časovača</h3><div class="bordersh3"></div><p>Ďalším aspektom, ktorý je potrebné zvážiť pri zmene časovača v hre na písanie, je celkový používateľský zážitok a rozhranie. Okrem nastavovania herného časovača pomocou tlačidiel je dôležité poskytnúť hráčom vizuálnu spätnú väzbu k zvolenému časovaču. Dá sa to dosiahnuť aktualizáciou iných prvkov na stránke, ako je napríklad zobrazenie odpočítavania. Po kliknutí na tlačidlo na nastavenie časovača by sa malo okamžite spustiť odpočítavanie, ktoré používateľovi poskytne spätnú väzbu v reálnom čase. To zaisťuje, že interakcia je plynulá a intuitívna, vďaka čomu je hra pútavejšia.</p><p>Na implementáciu môžete použiť JavaScript <b>setInterval</b> funkciu. Po nastavení časovača setInterval možno použiť na vytvorenie odpočítavania, ktoré každú sekundu znižuje hodnotu časovača. Keď časovač dosiahne nulu, funkcia môže buď zastaviť hru, alebo upozorniť používateľa, že čas vypršal. Táto funkcionalita v kombinácii s možnosťou dynamicky meniť časovač pomocou tlačidiel výrazne zlepšuje herný zážitok. Responzívne rozhranie je kľúčom k udržaniu zapojenia hráčov a spätná väzba v reálnom čase je jedným zo spôsobov, ako to dosiahnuť.</p><p>Okrem toho by sa malo zvážiť riešenie chýb. Ak sa napríklad používateľ pokúsi spustiť hru bez nastavenia časovača, môžete ho vyzvať správou, aby si vybral platný čas. Začlenením overovacích mechanizmov zaistíte, že hra bude fungovať hladko a znížite potenciálne problémy. Tento typ overovania nielen zlepšuje používateľský zážitok, ale prispieva aj k spoľahlivosti vašej hry, čím zaisťuje, že hráči nebudú čeliť zbytočnému zmätku.</p><div id="newfaq"><div id="adsense-article-faq"></div><h4 id="faq">Bežné otázky o prispôsobení časovača v JavaScripte</h4><div class="bordersh4"></div><ol> <li>Ako používam <strong>setInterval</strong> vytvoriť odpočítavanie?</li> <li>Môžete použiť <strong>setInterval</strong> nastavením tak, aby sa spúšťal každých 1000 milisekúnd (1 sekunda) a zakaždým znížením hodnoty časovača. Keď hodnota dosiahne nulu, môžete odpočítavanie zastaviť pomocou <strong>clearInterval</strong>.</li> <li>Aký je účel <strong>clearInterval</strong>?</li> <li><strong>clearInterval</strong> sa používa na zastavenie odpočítavania alebo akejkoľvek inej opakujúcej sa akcie, ktorú začal <strong>setInterval</strong>. Je dôležité zabezpečiť, aby sa odpočítavanie zastavilo, keď dosiahne nulu.</li> <li>Ako môžem dynamicky aktualizovať nadpis HTML?</li> <li>Použite <strong>document.title</strong> na nastavenie textu nadpisu stránky. Toto je možné aktualizovať v rámci vášho <strong>changeTimer</strong> funkcie na základe zvolenej časovej hodnoty.</li> <li>Môžem zvládnuť chyby používateľov pri výbere časovača?</li> <li>Áno, overenie môžete pridať tak, že pred spustením odpočítavania skontrolujete, či bola vybratá platná možnosť časovača. Ak nevyberiete žiadny platný čas, môžete zobraziť upozornenie alebo výzvu.</li> <li>Ako spustím funkciu po kliknutí na tlačidlo?</li> <li>Funkciu môžete k tlačidlu pripojiť pomocou <strong>addEventListener</strong> alebo priamym použitím <strong>onClick</strong> v prvku HTML tlačidla.</li></ol></div><div id="summary"><h4>Záverečné myšlienky na prispôsobenie časovača</h4><div class="bordersh4"></div><p>Začlenenie dynamických úprav časovača do hry na písanie výrazne zlepšuje hráčsky zážitok. Umožnením používateľom meniť časovač pomocou jednoduchých tlačidiel HTML a aktualizáciou rozhrania hry v reálnom čase môžu vývojári urobiť svoje hry interaktívnejšími a flexibilnejšími. Tento typ ovládania pomáha prispôsobiť sa rôznym úrovniam zručností.</p><p>Používanie osvedčených postupov, ako sú poslucháči udalostí, spracovanie chýb a testy jednotiek, zaisťuje, že hra beží hladko a poskytuje spoľahlivé používateľské prostredie. Implementácia týchto funkcií nielenže vylepší funkčnosť hry, ale tiež udrží hráčov vo väčšej miere vďaka citlivej a užívateľsky prívetivej mechanike.</p><div id="source"> <h6>Zdroje a odkazy na prispôsobenie časovača</h6> <div class="bordersh2"></div> <ol> <li>Podrobné informácie o používaní JavaScriptu na manipuláciu s DOM a spracovanie udalostí nájdete na <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide" target="_blank">Webové dokumenty MDN</a> .</li> <li>Pre pochopenie <a href="https://jestjs.io/docs/getting-started" target="_blank">Jest</a> framework a jeho implementácia pre testovanie jednotiek v aplikáciách JavaScript.</li> <li>Komplexné informácie o používaní <a href="https://www.w3schools.com/js/js_htmldom_eventlistener.asp" target="_blank">addEventListener</a> na spracovanie udalostí v JavaScripte sú dostupné na W3Schools.</li> <li>Dôležitosť aktualizácií v reálnom čase vo webových aplikáciách, vrátane časovačov, je diskutovaná v <a href="https://www.smashingmagazine.com/2020/02/real-time-app-web/" target="_blank">Smashing Magazine</a> .</li> </ol></div></div> </article> </div> <!-- WIDGET RIGHT SIDE SCREEN --> <div id="article-right" class="col-lg-3 ol-md-12 col-sm-12 col-xs-12"> <aside aria-label="sidebar" id="article-sidebar" class="sidebar sidebar-right"> <div id="adsense-right" class="widget sidebaritem d-none d-md-none d-lg-block adsense-right-vertical-div" page="0"> <!-- <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3922865260272328" crossorigin="anonymous"></script> <ins class="adsbygoogle adsense-right-vertical" style="" data-ad-client="ca-pub-3922865260272328" data-ad-slot="9756184449"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> --> </div> <div id="tempmail-slogan" class="widget w-about widget-sidebar sidebaritem" style="z-index:4;position:relative;background-color: white;margin-top:-30px;"> <div class="widget-title">Tempmail.us.com</div> <div class="bordersh4"></div> <p id="promotext">Hľadáte najvýkonnejší anonymný dočasný mail na internete? Naša bezplatná služba dočasnej pošty je najkomplexnejšia, Prijímanie a odosielanie e-mailov, Vytváranie presmerovaní na vaše obľúbené e-maily. Ponechajte si svoje heslo a používajte svoj dočasný e-mail po celý život. POP3, IMAP a SMTP k dispozícii zadarmo.</p> <div style="width:100%;text-align:right;"> <a class="read-more--with-arrow" href="https://www.tempmail.us.com/sk/"> Temp mail </a> </div> </div> <div id="adsense-article-square"></div> <div id="blog-ajax" style="margin-top:5px;"></div> </aside> </div> </div> </div> </section> <!-- Footer --> <svg width="100%" height="4px" xmlns="http://www.w3.org/2000/svg" class="border-footer"> <defs> <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%"> <stop offset="0%" style="stop-color:#EB177D;stop-opacity:1" /> <stop offset="25%" style="stop-color:#F9A933;stop-opacity:1" /> <stop offset="50%" style="stop-color:#3BC7EB;stop-opacity:1" /> <stop offset="75%" style="stop-color:#28C182;stop-opacity:1" /> </linearGradient> </defs> <rect width="100%" height="5px" fill="url(#grad1)" /> </svg> <!-- Balise div pour stocker le numéro de page initial --> <div id="content"> <!-- Contenu de votre page principale --> <div id="page_count"></div> </div> </div> <!-- ... end Footer --> <div id="javascript-mobile"></div> <script> // Fonction pour charger le script Hotjar function loadHotjar() { (function(h,o,t,j,a,r){ h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)}; h._hjSettings={hjid:5178820,hjsv:6}; a=o.getElementsByTagName('head')[0]; r=o.createElement('script');r.async=1; r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv; a.appendChild(r); })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv='); } // Écouteur d'événements pour la souris et le toucher if (typeof interactionDetected === 'undefined') { let interactionDetected = false; // Déclaration de la variable // Détecter les mouvements de souris sur desktop window.addEventListener('mousemove', function() { if (!interactionDetected) { interactionDetected = true; loadHotjar(); // Charge le script Hotjar } }); // Détecter les interactions tactiles sur mobile window.addEventListener('touchstart', function() { if (!interactionDetected) { interactionDetected = true; loadHotjar(); // Charge le script Hotjar } }); } </script> <script> // Function to load a script and return a Promise that resolves when the script is loaded function loadScript(src) { return new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = src; script.onload = () => resolve(); script.onerror = () => reject(new Error(`Failed to load script: ${src}`)); document.getElementById('javascript-mobile').appendChild(script); }); } // Async function to sequentially load scripts with a delay after jQuery async function loadScriptsSequentially() { try { // Load jQuery first await loadScript('https://www.tempmail.us.com/js/jquery.min.js'); // Optional: Verify that jQuery is loaded if (typeof jQuery === 'undefined') { throw new Error('jQuery did not load correctly.'); } // Delay of 500ms after jQuery is loaded //await new Promise(resolve => setTimeout(resolve, 100)); // Load the remaining scripts sequentially await loadScript('https://www.tempmail.us.com/js/lazysizes.min.js'); //await new Promise(resolve => setTimeout(resolve, 100)); //await loadScript('https://www.tempmail.us.com/js/load-bg-and-webp.js'); await loadScript('https://www.tempmail.us.com/js/prism.js'); // All scripts loaded successfully console.log('All scripts loaded successfully.'); // You can now execute any code that depends on the loaded scripts // For example: $(document).ready(function() { console.log('jQuery is ready.'); // Your jQuery-dependent code here }); } catch (error) { console.error(error); } } pageCount = document.querySelectorAll('#content #page_count').length; //console.log('Nombre de pages chargées:', pageCount); // Initiate the script loading based on the window width if (window.innerWidth < 900) { loadScriptsSequentially(); } </script> <script> setTimeout(function() { $(document).ready(function() { //permettre le copier-coller // Sélectionnez tous les éléments <pre> dans le document document.addEventListener('mousemove', function() { const pageCount = document.querySelectorAll('#content #page_count').length; //console.log('Nombre de pages chargées:', pageCount); pageNum = pageCount-1; var preElements = document.querySelectorAll('div[page="'+ pageNum +'"] pre'); // Parcourez chaque élément <pre> preElements.forEach(function(preElement, index) { var preId = "pre" + (index + 1); // ID unique, par exemple : pre1, pre2, pre3, ... // Créez un élément <img> avec un attribut onclick qui appelle copyCode avec l'ID correspondant var img = document.createElement("img"); img.src = "https://www.tempmail.us.com/img/copypaste4.png"; // Remplacez par le chemin de votre image img.alt = "Kopírovanie a vkladanie"; img.setAttribute("width", "28.698"); img.setAttribute("height", "35"); img.classList.add("lazyload"); img.setAttribute("onclick", "copyCode('" + preId + "', this)"); // Créez un élément div pour contenir l'image var imgContainer = document.createElement("div"); imgContainer.appendChild(img); imgContainer.classList.add("article-copypaste"); // Ajoutez la classe "article-copypaste" à la div // Insérez le imgContainer avant l'élément <pre> preElement.parentNode.insertBefore(imgContainer, preElement); // Attribuez l'ID à l'élément <pre> preElement.id = preId; }); var count = 1; $('.article-copypaste').each(function() { // Vérifie si la div langprog existe juste au-dessus de chaque div article-copypaste if ($(this).prev('.langprog').length === 0) { // Si elle n'existe pas, créez-la $(this).before('<p class="langprog"><br></p>'); } }); $('div[page="0"] .langprog').each(function() { //console.log("test"); // Créez une nouvelle div var newDiv = $('<div>').text(''); // Ajoutez des classes ou des styles à la nouvelle div si nécessaire newDiv.attr('id', "pre"+count+"-alert"); //newDiv.attr('display', "none"); // Ajoutez la nouvelle div en haut de la div actuelle $(this).prepend(newDiv); count++; }); document.removeEventListener('mousemove', arguments.callee); }); }); }, 1000); //copier les pre & code function copyCode(preId, button) { var pre = document.getElementById(preId); var range = document.createRange(); range.selectNode(pre); // Supprimer les espaces en début de chaque ligne var cleanedText = pre.textContent.replace(/^\s+/gm, ""); // Créer un élément temporaire pour copier le texte nettoyé var temp = document.createElement("textarea"); temp.value = cleanedText; document.body.appendChild(temp); temp.select(); document.execCommand("copy"); document.body.removeChild(temp); button.innerHTML = "Copié !"; setTimeout(function() { button.innerHTML = "Copier"; }, 1000); var boxe = "#"+preId+"-alert"; console.log(boxe); showCopyPaste(boxe,"Obsah bol skopírovaný do schránky!","success"); } function showCopyPaste(id,textbox,info) { var message = $('div[page="0"] ' + id); message.text(textbox); message.removeClass(); if (info=="general") { message.addClass('alert alert-secondary'); } if (info=="warning") { message.addClass('alert alert-warning'); } if (info=="danger") { message.addClass('alert alert-danger'); } if (info=="success") { message.addClass('alert alert-success'); } message.fadeIn(); setTimeout(function() { message.fadeOut(); }, 3000); // 2000 millisecondes = 2 secondes } </script> <script> setTimeout(function() { $(document).ready(function () { pageCount = document.querySelectorAll('#content #page_count').length; //console.log('Nombre de pages chargées:', pageCount); pageNum = pageCount-1; if ( pageNum==0) { //console.log("repasser par la "); initPositioning(0); // Initial call for the first page } setTimeout(function() { //parce que le prism est en defer Prism.highlightAll(); }, 500); }); $(document).ready(function () { var ajaxAborted = false; var page = 1; // Numéro de la page actuelle var loading = false; // Pour éviter les chargements multiples en même temps var articlesLoaded = false; function loadMoreArticles(unusedHeight) { if (loading || articlesLoaded) return; // Déclenche la requête AJAX pour charger plus d'articles $.ajax({ url: 'https://www.tempmail.us.com/02blog-ajax.php', // L'URL du script PHP pour charger les articles method: 'POST', data: { action: 'getArticles', lang: 'sk', addQueryCat: "AND catclean='javascript'", page: page, currentid: "100100", unusedHeight: unusedHeight // Utilisez la valeur de hauteur non utilisée ici }, dataType: 'html', beforeSend: function (xhr) { loading = true; if (ajaxAborted) { xhr.abort(); // Annuler la requête } }, success: function (response) { // Insérez les nouveaux articles dans la partie vide de la page if ($(response).find('div').length > 0) { const pageCount = document.querySelectorAll('#content #page_count').length; //console.log('Nombre de pages chargées:', pageCount); pageNum = pageCount-1; // La division en particulier est trouvée, continuez le traitement var parentDiv = $('div[page="' + pageNum + '"]'); var blogAjaxElement = parentDiv.find('#blog-ajax'); blogAjaxElement.append(response); } else { ajaxAborted = true; //console.log("aborded"); } // Incrémente le numéro de page page++; loading = false; articlesLoaded = true; }, error: function (xhr, status, error) { // Gérez les erreurs si nécessaire console.error(error); } }); } // Fonction pour calculer la hauteur non utilisée de manière synchrone function calculateUnusedHeight() { const pageCount = document.querySelectorAll('#content #page_count').length; //console.log('Nombre de pages chargées:', pageCount); pageNum = pageCount-1; var parentDiv = $('div[page="' + pageNum + '"]'); var sidebar = parentDiv.find('#article-right')[0]; var sidebarItems = parentDiv.find('.sidebaritem'); var $page = $('[page="' + pageNum + '"]'); var $article = $page.find('#article'); var $newfaq = $page.find('#newfaq'); var totalfaq = $newfaq.outerHeight(); $page.find('[id^=script]').each(function(index) { totalfaq += $(this).outerHeight(); }); //console.log("total height"+totalfaq ) // Comparer avec la hauteur de #article et ajuster si nécessaire var $article = $page.find('#article'); var realarticleheight = $article.outerHeight() - (totalfaq); var totalHeight = realarticleheight; if (totalfaq>realarticleheight) { totalHeight = totalfaq; } //console.log("test"+totalHeight); var itemsHeight = 0; for (var i = 0; i < sidebarItems.length; i++) { itemsHeight += sidebarItems[i].offsetHeight; } var $article = $page.find('#article'); var unusedHeight = $article.outerHeight() - 1600; //var unusedHeight = (totalHeight+400) - (itemsHeight); return unusedHeight; } // Chargez les premiers articles au chargement de la page if ($(window).width() > 991) { setTimeout(function() { var unusedHeight = calculateUnusedHeight(); //console.log("unUsed"+unusedHeight); loadMoreArticles(unusedHeight); }, 1500); } }); }, 1000); </script> <script> setTimeout(function() { $(document).ready(function() { // Fonction pour vérifier le statut de la publicité AdSense après un délai de 2 secondes setTimeout(function() { $(".adsbygoogle").each(function() { var self = $(this); var adStatus = self.attr("data-ad-status"); //console.log("test"+adStatus); if (adStatus === "unfilled") { removeParentDiv(self); // Appel de la fonction pour manipuler la div parent } }); }, 2000); // Attendre 2 secondes // Fonction pour manipuler la div parent function removeParentDiv(element) { var parentDiv = element.closest('#adsense-right'); if (parentDiv.length > 0) { parentDiv.remove(); // Supprimer la div parent si elle est trouvée } } }); }, 1000); // Écoute de l'événement de mouvement de la souris pour charger le script Google AdSense lorsque l'utilisateur effectue une action document.addEventListener('mousemove', function() { // Chargement du script Google AdSense //chargerScriptGoogleAdsenseVertical(); var script = document.createElement('script'); script.src = 'https://www.googletagmanager.com/gtag/js?id=G-ESDTKX54VK'; script.async = true; // Ajoutez le script à l'en-tête du document document.head.appendChild(script); // Initialisez Google Tag Manager lorsque le script est chargé script.onload = function() { window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-ESDTKX54VK'); }; chargerScriptGoogleAdsenseSquare(); // Suppression de l'écouteur d'événements après le premier déclenchement pour éviter de charger le script à nouveau document.removeEventListener('mousemove', arguments.callee); }); // Fonction pour charger le script Google AdSense function chargerScriptGoogleAdsenseSquare() { // Créez un élément script var script = document.createElement('script'); script.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3922865260272328"; script.async = true; script.crossOrigin = "anonymous"; // Ajoutez une fonction pour exécuter lorsque le script est chargé script.onload = function() { // Créez un élément ins (bloc de publicité AdSense) var ins = document.createElement('ins'); ins.className = "adsbygoogle adsense-right-square"; ins.style = ""; ins.setAttribute('data-ad-client', 'ca-pub-3922865260272328'); ins.setAttribute('data-ad-slot', '2613927101'); // ins.setAttribute('data-ad-format', 'auto'); // ins.setAttribute('data-full-width-responsive', 'true'); // Ajoutez le bloc de publicité à l'emplacement désiré var parentElement = document.querySelector('div[page="0"] .widget.adsenselink.d-none.d-md-none.d-lg-block'); parentElement.appendChild(ins); // Appelez la fonction push() pour afficher la publicité (adsbygoogle = window.adsbygoogle || []).push({}); // Surveillez les changements de l'attribut data-ad-status de l'élément ins var observer = new MutationObserver(function(mutationsList, observer) { mutationsList.forEach(function(mutation) { if (mutation.attributeName === "data-ad-status") { // Récupérez la valeur de l'attribut data-ad-status var status = ins.getAttribute("data-ad-status"); //console.log("Attribut data-ad-status a changé :", status); // Faites ce que vous devez avec la valeur récupérée if (status != "filled") { $('#adsense-right').remove(); // Appel de la fonction pour manipuler la div parent } } }); }); // Configurez l'observateur pour surveiller les changements d'attribut de l'élément ins observer.observe(ins, { attributes: true }); }; // Ajoutez le script à l'emplacement désiré var parentElement = document.querySelector('div[page="0"] .widget.adsenselink.d-none.d-md-none.d-lg-block'); parentElement.appendChild(script); } function chargerScriptGoogleAdsenseVertical() { // Création de l'élément script var script = document.createElement('script'); script.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3922865260272328"; script.async = true; script.crossOrigin = "anonymous"; // Ajout d'une fonction à exécuter lorsque le script est chargé script.onload = function() { // Création de l'élément ins (bloc de publicité AdSense) var ins = document.createElement('ins'); ins.className = "adsbygoogle adsense-right-vertical"; ins.style = ""; ins.setAttribute('data-ad-client', 'ca-pub-3922865260272328'); ins.setAttribute('data-ad-slot', '9756184449'); // Ajout du bloc de publicité à l'emplacement désiré var parentElement = document.querySelector('div[page="0"] .widget.sidebaritem.d-none.d-md-none.d-lg-block.adsense-right-vertical-div'); parentElement.appendChild(ins); // Appel de la fonction push() pour afficher la publicité (adsbygoogle = window.adsbygoogle || []).push({}); var observer = new MutationObserver(function(mutationsList, observer) { mutationsList.forEach(function(mutation) { if (mutation.attributeName === "data-ad-status") { // Récupérez la valeur de l'attribut data-ad-status var status = ins.getAttribute("data-ad-status"); console.log("Attribut data-ad-status a changé :", status); // Faites ce que vous devez avec la valeur récupérée if (status != "filled") { document.querySelector('div[page="0"] .widget.sidebaritem.d-none.d-md-none.d-lg-block.adsense-right-vertical-div').remove(); // Appel de la fonction pour manipuler la div parent } } }); }); // Configurez l'observateur pour surveiller les changements d'attribut de l'élément ins observer.observe(ins, { attributes: true }); }; // Ajout du script à l'emplacement désiré var parentElement = document.querySelector('div[page="0"] .widget.sidebaritem.d-none.d-md-none.d-lg-block.adsense-right-vertical-div'); parentElement.appendChild(script); } </script> <script> function handleScroll() { var scrollPosition = window.scrollY; // Position de défilement par rapport au haut de la page var targetDiv = document.getElementById('navigation'); // Remplacez 'votre-div' par l'ID de votre div cible // Si la position de défilement est supérieure à 0, ajoutez la classe if (scrollPosition > 0) { targetDiv.classList.add('header--fixed'); // Remplacez 'votre-classe' par le nom de la classe que vous souhaitez ajouter } else { // Sinon, supprimez la classe targetDiv.classList.remove('header--fixed'); } } // Écoutez l'événement de défilement window.addEventListener('scroll', handleScroll); </script> <script> setTimeout(function() { $(document).ready(function () { // Définir une variable globale pour vérifier si la nouvelle page a été chargée let nouvellePageChargee = false; // Fonction pour charger la page suivante function chargerPageSuivante(url) { // Charger le contenu de la page suivante via AJAX ou fetch fetch(url) .then(response => response.text()) .then(data => { // Créer un nouvel élément div pour contenir le contenu HTML const tempDiv = document.createElement('div'); tempDiv.innerHTML = data; var navigationLogoElements = tempDiv.querySelectorAll('.navigation-logo'); // Parcourir tous les éléments trouvés et ajouter un style pour les cacher navigationLogoElements.forEach(function(element) { element.style.display = 'none'; }); var h1ArticleElement = tempDiv.querySelector('#h1article'); // Appliquer le style à l'élément sélectionné if (h1ArticleElement) { h1ArticleElement.style.marginBottom = '46px'; h1ArticleElement.style.marginTop = '0px'; h1ArticleElement.style.marginLeft = '10px'; } var articleheader = tempDiv.querySelector('#article-header'); if (articleheader) { articleheader.style.paddingBottom = '20px'; articleheader.style.paddingTop = '20px'; } var h1header = tempDiv.querySelector('#h1article'); if (h1header) { h1header.style.maxWidth = '70%'; } var screenWidth = window.innerWidth; var imgElement = tempDiv.querySelector('.article-main-img'); if (screenWidth > 900 && imgElement) { imgElement.src = 'https://www.tempmail.us.com/images/80/80738e14f3a3bf39f19b55b8d7992fe0.png/vyzvy-pri-vykonavani-ulozenych-procedur-zalozenych-na-javascripte-v-snowflake-prostrednictvom-airflow-dag.png'; } var desktoplogo = tempDiv.querySelector('.newlogo-desktop'); if (desktoplogo) { var imgElement = document.createElement("img"); imgElement.className = "lazyload"; imgElement.alt = "Temp mail SuperHeros"; if (window.innerWidth > 900) { imgElement.src = "https://www.tempmail.us.com/images/site/tempmail-superheros.webp"; imgElement.width = 343; imgElement.height = 350; desktoplogo.appendChild(imgElement); } } var adsensearticle = tempDiv.querySelector('#adsense-article'); if (adsensearticle) { var scriptElement = document.createElement('script'); scriptElement.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3922865260272328"; scriptElement.async = true; scriptElement.crossorigin = "anonymous"; var insElement = document.createElement('ins'); insElement.className = "adsbygoogle"; insElement.style.display = "block"; insElement.setAttribute('data-ad-client', 'ca-pub-3922865260272328'); insElement.setAttribute('data-ad-slot', '4326653974'); insElement.setAttribute('style', 'display:inline-block;max-width:100%;width:100%;min-height:140px;max-height:140px;padding-top:10px;padding-bottom:0px;'); // Insertion des éléments dans la div #index-adsense var adsContainer = tempDiv.querySelector('#adsense-article'); // adsContainer.style.border = "2px solid #dfe6ec"; // adsContainer.style.paddingTop = "5px"; //adsContainer.style.marginTop = "5px"; // adsContainer.style.height = "110px"; // adsContainer.style.paddingBottom = "0px"; //adsContainer.style.marginBottom = "5px"; // adsContainer.style.backgroundColor = "#f7f8fa"; // adsContainer.style.borderRadius = "5px"; adsContainer.appendChild(scriptElement); adsContainer.appendChild(insElement); } var adsensearticlefaq = tempDiv.querySelector('#adsense-article-faq'); if (adsensearticlefaq) { var scriptElement = document.createElement('script'); scriptElement.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3922865260272328"; scriptElement.async = true; scriptElement.crossorigin = "anonymous"; var insElement = document.createElement('ins'); insElement.className = "adsbygoogle"; insElement.style.display = "block"; insElement.setAttribute('data-ad-client', 'ca-pub-3922865260272328'); insElement.setAttribute('data-ad-slot', '4326653974'); insElement.setAttribute('style', 'display:inline-block;max-width:100%;width:100%;min-height:140px;max-height:140px;padding-top:10px;padding-bottom:0px;'); // Insertion des éléments dans la div #index-adsense var adsContainer = tempDiv.querySelector('#adsense-article-faq'); // adsContainer.style.border = "2px solid #dfe6ec"; // adsContainer.style.paddingTop = "5px"; //adsContainer.style.marginTop = "5px"; // adsContainer.style.height = "110px"; // adsContainer.style.paddingBottom = "0px"; //adsContainer.style.marginBottom = "5px"; // adsContainer.style.backgroundColor = "#f7f8fa"; // adsContainer.style.borderRadius = "5px"; adsContainer.appendChild(scriptElement); adsContainer.appendChild(insElement); } var adsensearticlefaq = tempDiv.querySelector('#adsense-article-square'); if (adsensearticlefaq) { var scriptElement = document.createElement('script'); scriptElement.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3922865260272328"; scriptElement.async = true; scriptElement.crossorigin = "anonymous"; var insElement = document.createElement('ins'); insElement.className = "adsbygoogle"; insElement.style.display = "block"; insElement.setAttribute('data-ad-client', 'ca-pub-3922865260272328'); insElement.setAttribute('data-ad-slot', '4326653974'); insElement.setAttribute('style', 'display:inline-block;width:100%;height:auto;max-width:100%;min-height:350px;max-height:350px;margin-top:10px;margin-bottom:8px;'); // Insertion des éléments dans la div #index-adsense var adsContainer = tempDiv.querySelector('#adsense-article-square'); // adsContainer.style.border = "2px solid #dfe6ec"; // adsContainer.style.paddingTop = "5px"; //adsContainer.style.marginTop = "5px"; // adsContainer.style.height = "110px"; // adsContainer.style.paddingBottom = "0px"; //adsContainer.style.marginBottom = "5px"; // adsContainer.style.backgroundColor = "#f7f8fa"; // adsContainer.style.borderRadius = "5px"; adsContainer.appendChild(scriptElement); adsContainer.appendChild(insElement); } const pageCount = document.querySelectorAll('#content #page_count').length; //console.log('Nombre de pages chargées:', pageCount); // Récupérer tous les éléments avec l'attribut page=1 dans tempDiv const elementsWithPageAttribute = tempDiv.querySelectorAll('[page="0"]'); // Mettre à jour les attributs de ces éléments avec la valeur de pageCount elementsWithPageAttribute.forEach(element => { element.setAttribute('page', pageCount); }); // Extraire et exécuter les scripts de la nouvelle page const scripts = tempDiv.querySelectorAll('script'); scripts.forEach(script => { if (script.type !== 'application/ld+json') { const newScript = document.createElement('script'); // Modifier le contenu du script pour mettre à jour les sélecteurs let scriptContent = script.textContent; // Vérifier si le script contient 'page="0"' et le remplacer par la nouvelle valeur de pageCount // Si le script a un attribut src, le copier if (script.src) { newScript.src = script.src; } else { // Sinon, copier le contenu du script let scriptContent = script.textContent; // Remplacer toutes les occurrences de 'div[page="0"]' par 'div[page="' + pageCount + '"]' scriptContent = scriptContent.replace(/div\[page="0"\]/g, 'div[page="' + pageCount + '"]'); // Assigner le nouveau contenu au script newScript.textContent = scriptContent; } console.log(newScript) document.body.appendChild(newScript); } }); // Ajouter le contenu de la nouvelle page à la page actuelle document.getElementById('content').appendChild(tempDiv); if (pageCount!=0) { initPositioning(pageCount); (adsbygoogle = window.adsbygoogle || []).push({}); (adsbygoogle = window.adsbygoogle || []).push({}); (adsbygoogle = window.adsbygoogle || []).push({}); } // Compter le nombre de div avec l'ID "page_count" }) .catch(error => { console.error('Erreur lors du chargement de la page suivante:', error); }); } // Événement de défilement de la fenêtre window.addEventListener('scroll', function() { // Vérifier si l'utilisateur a atteint le bas de la page var distanceRestante = document.body.offsetHeight - (window.innerHeight + window.scrollY); // Vérifier si l'utilisateur est près du bas de la page if (!nouvellePageChargee && ($(window).scrollTop() + $(window).height()) >= $(document).height() - 100) { // Mettre à jour l'URL dans la barre d'adresse du navigateur avec l'URL de la page suivante window.history.pushState({}, '', 'https://www.tempmail.us.com/sk/snowflake/vyzvy-pri-vykonavani-ulozenych-procedur-zalozenych-na-javascripte-v-snowflake-prostrednictvom-airflow-dag'); // Charger la page suivante chargerPageSuivante('https://www.tempmail.us.com/sk/snowflake/vyzvy-pri-vykonavani-ulozenych-procedur-zalozenych-na-javascripte-v-snowflake-prostrednictvom-airflow-dag'); // Désactiver le gestionnaire d'événements de défilement window.removeEventListener('scroll', arguments.callee); } }); }); }, 1000); </script> <script> setTimeout(function() { $(document).ready(function() { //mobile image top load after pour le page speed var imageLoaded = false; // Pour vérifier si l'image a déjà été chargée $(document).on('touchstart', '*', function(event) { if (!imageLoaded) { var $image = $('#lazyImage'); var imageSrc = $image.data('src'); // Récupère l'URL de l'image depuis data-src // Modifie le src de l'image pour charger l'image $image.attr('src', imageSrc); $image.css('min-width', '109%').css('!important', true); $image.css('height', '250px').css('!important', true); // Marque l'image comme chargée imageLoaded = true; // Optionnel : Désactiver l'écoute de l'événement après chargement pour éviter les appels répétés $(document).off('touchstart'); } }); }); }, 1000); function initPositioning(pageCount) { if ($(window).width() > 1700) { var $page = $('[page="' + pageCount + '"]'); console.log("page count"+pageCount); var $newfaq = $page.find('#newfaq'); if ($newfaq.length) { var topOffset = 75 + $newfaq.outerHeight() - 30; var leftOffset = $newfaq.position().left + 30; //fixed mac issues if ($(window).width()==2072) { leftOffset = $newfaq.position().left + 180; } if ($(window).width()==1792) { leftOffset = $newfaq.position().left + 90; } if ($(window).width()==1728) { leftOffset = $newfaq.position().left + 130; } if ($(window).width()==2030) { leftOffset = $newfaq.position().left + 190; } // Calculer la hauteur totale de #newfaq et des scripts var totalHeight = $newfaq.outerHeight(); console.log("CALCUL LA HAUTEUR DU FAQ TOTALHEIGHT"+totalHeight) var $article = $page.find('#article'); var realarticleheight = $article.outerHeight() - totalHeight; //console.log("REGARDER LA HAUTEUR DE L'ARTICLE SANS FAQ"+realarticleheight) //si ya plus de contenue à droite on update sont height if (totalHeight > realarticleheight) { // $article.css('height', totalHeight + 'px'); } var $summary = $page.find('#summary'); if ($summary.length) { var summaryHeight = $summary.outerHeight(); //console.log("SUMMARY HAUTEUR SI DISPONIBLE "+summaryHeight) } // Réinitialiser topOffset après ajustement de #article topOffset = $newfaq.position().top + $newfaq.outerHeight() - 50; // Positionner les divs script pour chaque page $page.find('[id^=script]').each(function(index) { $(this).css({ 'position': 'absolute', 'top': topOffset + 'px', 'left': leftOffset + 'px' }); topOffset += $(this).outerHeight(); }); var totalHeight = $newfaq.outerHeight(); $page.find('[id^=script]').each(function(index) { if ($(this).css('position') === 'absolute') { totalHeight += $(this).outerHeight(); } }); //console.log("CALCUL LA HAUTEUR DU FAQ + SCRIPT absolute TOTALHEIGHT"+totalHeight) setTimeout(function() { if ($("#source").length) { var source = $page.find('#source'); var sourceHeight = source.outerHeight(); } var realarticleheight = $article.outerHeight(); var totalleft = realarticleheight; var totalright = totalHeight-700; console.log("total left "+totalleft) console.log("total right"+totalright) console.log("summary height"+summaryHeight) console.log("source height"+sourceHeight) if ($("#source").length) { if ((totalleft-totalright)>(summaryHeight+sourceHeight)) { $summary.css({ 'position': 'absolute', 'top': (topOffset-50) + 'px', 'left': leftOffset + 'px', 'max-width': '950px' }); source.css({ 'max-width': '950px' }); if ($(window).width()<2000) { $summary.css({ 'max-width': '750px' }); source.css({ 'max-width': '750px' }); } var newrightheight = topOffset+summaryHeight+550; console.log("new right height"+newrightheight) console.log("totalleft"+totalleft) if (newrightheight>totalleft) { console.log("test") // $article.css('height', newrightheight-500 + 'px'); } } } else { if ((totalleft-totalright)>(summaryHeight)) { $summary.css({ 'position': 'absolute', 'top': (topOffset-50) + 'px', 'left': leftOffset + 'px', 'max-width': '950px' }); if ($(window).width()<2000) { $summary.css({ 'max-width': '750px' }); } var newrightheight = topOffset+summaryHeight+550; console.log("new right height"+newrightheight) console.log("totalleft"+totalleft) if (newrightheight>totalleft) { console.log("test") // $article.css('height', newrightheight-500 + 'px'); } } } }, 1000); //si le summary est disponible et que le totalheight+smuaarry sont plus petit on le déplace a droite //SI LE SUMMARY À DROITE PEUT ETRE MISE À GAUCHE POUR BALANCER LA PAGE /* if ((totalHeight+summaryHeight) < ((realarticleheight-summaryHeight))) { } var $source = $page.find('#source'); if ($(window).width()>2000) { $source.css({ 'position': 'absolute', 'top': (topOffset-50) + 'px', 'left': leftOffset + 'px', 'max-width': '950px' }); } else { $source.css({ 'position': 'absolute', 'top': (topOffset-50) + 'px', 'left': leftOffset + 'px', 'max-width': '750px' }); } */ //------------------------------------------------------------------------ //ON RECALCUL LE CÖTÉ DROITE APRÈS LES MODIFICATION ET ON CONFIRME LE GAUCHE var totalHeight = $newfaq.outerHeight(); $page.find('[id^=script]').each(function(index) { if ($(this).css('position') === 'absolute') { totalHeight += $(this).outerHeight(); } }); if ($summary.length) { totalHeight = totalHeight+$('#summary').outerHeight(); } var elements = []; $page.find('[id^=script]').each(function() { elements.push($(this)); }); // Sort the array by ID in descending order elements.sort(function(a, b) { var aNum = parseInt(a.attr('id').replace('script', '')); var bNum = parseInt(b.attr('id').replace('script', '')); return bNum - aNum; }); //console.log("TOTAL HEIGHT VALUE 1 -> "+totalHeight) var $article = $page.find('#article'); realarticleheight = $article.outerHeight(); //console.log("realarticleheight VALUE 1 -> "+realarticleheight ) //-------------------------------------------------------------------- //-------------------------------------------------------------------- SI LE CÖTÉ DROITE EST PLUS LONG QUE LE CÖTÉ GAUCHE if (totalHeight > realarticleheight) { //console.log("TOTAL HEIGHT + GRAND QUE realarticleheight") var difference = totalHeight - realarticleheight; var lastStaticElement = null; if (difference > 500) { elements.forEach(function(item) { if ((difference - item.outerHeight()) > 0) { // Mark the last element that should be static lastStaticElement = item; item.css({ 'position': 'static', 'top': '', 'left': '' }); } // Update the difference for the next iteration difference -= item.outerHeight(); }); // Apply 'static' only to the last element if it exists if (lastStaticElement) { lastStaticElement.css({ 'position': 'static', 'top': '', 'left': '' }); } } var totalHeight = $newfaq.outerHeight(); $page.find('[id^=script]').each(function(index) { if ($(this).css('position') === 'absolute') { totalHeight += $(this).outerHeight(); } }); var $article = $page.find('#article'); realarticleheight = $article.outerHeight(); var difference = totalHeight - realarticleheight; setTimeout(function() { console.log("difference "+difference); /*if (difference > 500) { $summary.css({ 'position': 'absolute', 'top': topOffset + 'px', 'left': leftOffset + 'px' }); } */ // if (difference > 500) { $summary.css({ 'position': 'static', 'top': '', 'left': '' }); //} console.log("passer par la") var $article = $page.find('#article'); // $article.css('height', '11px'); if ($summary.length) { var summaryHeight = $summary.outerHeight(); if ($summary.css('position') === 'absolute') { totalHeight = totalHeight; // $article.css('height', totalHeight + 'px'); } } //console.log("TOTAL HEIGHT APRÈS DÉPLACEMENT VERS LA DROITE "+totalHeight) var $article = $page.find('#article'); //console.log("ARTICLE HEIGHT APRÈS DÉPLACEMENT VER LA DROITE "+$article.outerHeight()) if (totalHeight>$article.outerHeight()) { // $article.css('height', totalHeight+800 + 'px'); } }, 2000); } //-------------------------------------------------------------------- } } } </script> <script> document.addEventListener("DOMContentLoaded", function() { var imgElement = document.createElement("img"); imgElement.className = "lazyload"; imgElement.alt = "Temp mail SuperHeros"; if (window.innerWidth > 900) { imgElement.src = "https://www.tempmail.us.com/images/site/tempmail-superheros.webp"; imgElement.width = 343; imgElement.height = 350; document.querySelector(".newlogo-desktop").appendChild(imgElement); var img = document.getElementById("article-logo"); if (img) { img.src = "https://www.tempmail.us.com/images/site/logo-95px.webp"; img.width = 95; img.height = 90; } } else { imgElement.src = "https://www.tempmail.us.com/images/site/tempmail-superheros-mobile.webp"; imgElement.width = 147; imgElement.height = 150; document.querySelector(".newlogo").appendChild(imgElement); } }); document.addEventListener("DOMContentLoaded", function() { var imageBackgroundDiv = document.getElementById('image-background'); if (!imageBackgroundDiv) return; // Exit if the div doesn't exist var bg320 = imageBackgroundDiv.getAttribute('data-bg-320'); var bg540 = imageBackgroundDiv.getAttribute('data-bg-540'); var bg768 = imageBackgroundDiv.getAttribute('data-bg-768'); var bg1366 = imageBackgroundDiv.getAttribute('data-bg-1366'); var bg1536 = imageBackgroundDiv.getAttribute('data-bg-1536'); var bg1920 = imageBackgroundDiv.getAttribute('data-bg-1920'); var bg2732 = imageBackgroundDiv.getAttribute('data-bg-2732'); var screenWidth = window.innerWidth; if (screenWidth <= 320) { imageBackgroundDiv.style.backgroundImage = `url(${bg320})`; } else if (screenWidth <= 540) { imageBackgroundDiv.style.backgroundImage = `url(${bg540})`; } else if (screenWidth <= 768) { imageBackgroundDiv.style.backgroundImage = `url(${bg768})`; } else if (screenWidth <= 1366) { imageBackgroundDiv.style.backgroundImage = `url(${bg1366})`; } else if (screenWidth <= 1536) { imageBackgroundDiv.style.backgroundImage = `url(${bg1536})`; } else if (screenWidth <= 1920) { imageBackgroundDiv.style.backgroundImage = `url(${bg1920})`; } else { imageBackgroundDiv.style.backgroundImage = `url(${bg2732})`; } }); </script> <script> document.addEventListener("DOMContentLoaded", function() { var screenWidth = window.innerWidth; var imgElement = document.querySelector('.article-main-img'); if (screenWidth > 900 && imgElement) { imgElement.src = 'https://www.tempmail.us.com/images/9a/9a679053963ebb61b232c79134b8a627-766px.webp/ako-upravit-hodnotu-casovaca-javascript-pre-hru-na-pisanie-pomocou-tlacidiel-html-766px.webp'; } }); </script> <script> document.addEventListener("DOMContentLoaded", function() { document.addEventListener('mousemove', function() { var windowWidth = window.innerWidth; if (windowWidth > 900) { var scriptElement = document.createElement('script'); scriptElement.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3922865260272328"; scriptElement.async = true; scriptElement.crossorigin = "anonymous"; var insElement = document.createElement('ins'); insElement.className = "adsbygoogle"; insElement.style.display = "block"; insElement.setAttribute('data-ad-client', 'ca-pub-3922865260272328'); insElement.setAttribute('data-ad-slot', '4326653974'); insElement.setAttribute('style', 'display:inline-block;max-width:100%;width:100%;min-height:140px;max-height:140px;padding-top:10px;padding-bottom:0px;'); // Insertion des éléments dans la div #index-adsense var adsContainer = document.getElementById("adsense-article"); // adsContainer.style.border = "2px solid #dfe6ec"; // adsContainer.style.paddingTop = "5px"; //adsContainer.style.marginTop = "5px"; // adsContainer.style.height = "110px"; // adsContainer.style.paddingBottom = "0px"; //adsContainer.style.marginBottom = "5px"; // adsContainer.style.backgroundColor = "#f7f8fa"; // adsContainer.style.borderRadius = "5px"; adsContainer.appendChild(scriptElement); adsContainer.appendChild(insElement); (adsbygoogle = window.adsbygoogle || []).push({}); // Création des éléments script et ins var scriptElement = document.createElement('script'); scriptElement.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3922865260272328"; scriptElement.async = true; scriptElement.crossorigin = "anonymous"; var insElement = document.createElement('ins'); insElement.className = "adsbygoogle"; insElement.style.display = "block"; insElement.setAttribute('data-ad-client', 'ca-pub-3922865260272328'); insElement.setAttribute('data-ad-slot', '4395216949'); insElement.setAttribute('style', 'display:block;width:100%;height:auto;max-width:100%;min-height:140px;max-height:140px;margin-top:10px;margin-bottom:8px;'); var adsContainer = document.getElementById("adsense-article-faq"); // adsContainer.style.border = "2px solid #dfe6ec"; // adsContainer.style.paddingTop = "10px"; // adsContainer.style.paddingBottom = "0px"; // adsContainer.style.marginBottom = "10px"; // adsContainer.style.height = "110px"; // adsContainer.style.backgroundColor = "#f7f8fa"; // adsContainer.style.borderRadius = "5px"; if (adsContainer) { adsContainer.appendChild(scriptElement); adsContainer.appendChild(insElement); // Rechargez les annonces pour qu'elles soient affichées correctement (adsbygoogle = window.adsbygoogle || []).push({}); } // Création des éléments script et ins var scriptElement = document.createElement('script'); scriptElement.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3922865260272328"; scriptElement.async = true; scriptElement.crossorigin = "anonymous"; var insElement = document.createElement('ins'); insElement.className = "adsbygoogle"; insElement.style.display = "block"; insElement.setAttribute('data-ad-client', 'ca-pub-3922865260272328'); insElement.setAttribute('data-ad-slot', '4395216949'); insElement.setAttribute('style', 'display:inline-block;width:100%;height:auto;max-width:100%;min-height:350px;max-height:350px;margin-top:10px;margin-bottom:8px;'); var adsContainer = document.getElementById("adsense-article-square"); // adsContainer.style.border = "2px solid #dfe6ec"; // adsContainer.style.paddingTop = "10px"; // adsContainer.style.paddingBottom = "0px"; // adsContainer.style.marginBottom = "10px"; // adsContainer.style.height = "110px"; // adsContainer.style.backgroundColor = "#f7f8fa"; // adsContainer.style.borderRadius = "5px"; if (adsContainer) { adsContainer.appendChild(scriptElement); adsContainer.appendChild(insElement); // Rechargez les annonces pour qu'elles soient affichées correctement (adsbygoogle = window.adsbygoogle || []).push({}); } } document.removeEventListener('mousemove', arguments.callee); }); }); setTimeout(function() { var pubLoaded = false; // Pour vérifier si l'image a déjà été chargée $(document).on('touchstart', '*', function(event) { if (!pubLoaded) { // Marque la pub comme chargée pubLoaded = true; // Optionnel : Désactiver l'écoute de l'événement après chargement pour éviter les appels répétés $(document).off('touchstart'); var windowWidth = window.innerWidth; if (windowWidth < 900) { var scriptElement = document.createElement('script'); scriptElement.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3922865260272328"; scriptElement.async = true; scriptElement.crossorigin = "anonymous"; var insElement = document.createElement('ins'); insElement.className = "adsbygoogle"; insElement.style.display = "block"; insElement.setAttribute('data-ad-client', 'ca-pub-3922865260272328'); insElement.setAttribute('data-ad-slot', '4326653974'); insElement.setAttribute('style', 'display:inline-block;max-width:100%;width:100%;min-height:140px;max-height:140px;padding-top:10px;padding-bottom:0px;'); // Insertion des éléments dans la div #index-adsense var adsContainer = document.getElementById("adsense-article"); // adsContainer.style.border = "2px solid #dfe6ec"; // adsContainer.style.paddingTop = "5px"; //adsContainer.style.marginTop = "5px"; // adsContainer.style.height = "110px"; // adsContainer.style.paddingBottom = "0px"; //adsContainer.style.marginBottom = "5px"; // adsContainer.style.backgroundColor = "#f7f8fa"; // adsContainer.style.borderRadius = "5px"; adsContainer.appendChild(scriptElement); adsContainer.appendChild(insElement); (adsbygoogle = window.adsbygoogle || []).push({}); // Création des éléments script et ins var scriptElement = document.createElement('script'); scriptElement.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3922865260272328"; scriptElement.async = true; scriptElement.crossorigin = "anonymous"; var insElement = document.createElement('ins'); insElement.className = "adsbygoogle"; insElement.style.display = "block"; insElement.setAttribute('data-ad-client', 'ca-pub-3922865260272328'); insElement.setAttribute('data-ad-slot', '4395216949'); insElement.setAttribute('style', 'display:block;width:100%;height:auto;max-width:100%;min-height:140px;max-height:140px;margin-top:10px;margin-bottom:8px;'); var adsContainer = document.getElementById("adsense-article-faq"); // adsContainer.style.border = "2px solid #dfe6ec"; // adsContainer.style.paddingTop = "10px"; // adsContainer.style.paddingBottom = "0px"; // adsContainer.style.marginBottom = "10px"; // adsContainer.style.height = "110px"; // adsContainer.style.backgroundColor = "#f7f8fa"; // adsContainer.style.borderRadius = "5px"; if (adsContainer) { adsContainer.appendChild(scriptElement); adsContainer.appendChild(insElement); // Rechargez les annonces pour qu'elles soient affichées correctement (adsbygoogle = window.adsbygoogle || []).push({}); } // Création des éléments script et ins var scriptElement = document.createElement('script'); scriptElement.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3922865260272328"; scriptElement.async = true; scriptElement.crossorigin = "anonymous"; var insElement = document.createElement('ins'); insElement.className = "adsbygoogle"; insElement.style.display = "block"; insElement.setAttribute('data-ad-client', 'ca-pub-3922865260272328'); insElement.setAttribute('data-ad-slot', '4395216949'); insElement.setAttribute('style', 'display:inline-block;width:100%;height:auto;max-width:100%;min-height:350px;max-height:350px;margin-top:10px;margin-bottom:8px;'); var adsContainer = document.getElementById("adsense-article-square"); // adsContainer.style.border = "2px solid #dfe6ec"; // adsContainer.style.paddingTop = "10px"; // adsContainer.style.paddingBottom = "0px"; // adsContainer.style.marginBottom = "10px"; // adsContainer.style.height = "110px"; // adsContainer.style.backgroundColor = "#f7f8fa"; // adsContainer.style.borderRadius = "5px"; if (adsContainer) { adsContainer.appendChild(scriptElement); adsContainer.appendChild(insElement); // Rechargez les annonces pour qu'elles soient affichées correctement (adsbygoogle = window.adsbygoogle || []).push({}); } } } }); }, 1000); </script> </body> </html>