Cách sửa đổi giá trị bộ đếm thời gian JavaScript cho trò chơi đánh máy bằng các nút HTML

Cách sửa đổi giá trị bộ đếm thời gian JavaScript cho trò chơi đánh máy bằng các nút HTML
Cách sửa đổi giá trị bộ đếm thời gian JavaScript cho trò chơi đánh máy bằng các nút HTML

Điều chỉnh hẹn giờ động để gõ trò chơi bằng nút

Trong một trò chơi đánh máy, việc kiểm soát nhịp độ của trò chơi là rất quan trọng để đảm bảo trải nghiệm hấp dẫn cho người dùng. Một yếu tố quan trọng là bộ đếm thời gian, xác định thời gian người dùng phải hoàn thành trò chơi hoặc thử thách đánh máy. Bằng cách cho phép người dùng điều chỉnh bộ đếm thời gian của trò chơi thông qua các nút HTML đơn giản, bạn có thể cung cấp cho họ nhiều quyền kiểm soát hơn đối với lối chơi của mình.

Bài viết này sẽ hướng dẫn bạn cách tạo một giải pháp trong JavaScript cho phép người chơi lựa chọn giữa các cài đặt hẹn giờ khác nhau bằng cách sử dụng các nút. Ví dụ: chọn nút '30 giây' sẽ điều chỉnh bộ hẹn giờ thành 30 giây, trong khi nhấp vào nút '60 giây' sẽ thay đổi thành 60 giây.

Hàm JavaScript sẽ lấy giá trị từ nút được nhấp và cập nhật động cả bộ đếm thời gian và tiêu đề trò chơi. Tính linh hoạt này có thể nâng cao trải nghiệm người dùng, giúp trò chơi trở nên tùy biến hơn và thú vị hơn đối với các cấp độ kỹ năng khác nhau.

Đến cuối hướng dẫn này, bạn sẽ có tính năng điều chỉnh hẹn giờ đầy đủ chức năng bằng cách sử dụng HTML và JavaScript. Chúng tôi cũng sẽ đề cập đến cách cập nhật giá trị bộ hẹn giờ được hiển thị trên tiêu đề của trang để phản ánh thời lượng bộ hẹn giờ đã chọn.

Yêu cầu Ví dụ về sử dụng
document.querySelector() Được sử dụng để chọn phần tử HTML nhằm cập nhật động tiêu đề của tab trình duyệt. Phương pháp này dành riêng cho việc chọn các thành phần dựa trên bộ chọn CSS của chúng và ở đây nó giúp thay đổi tiêu đề trang dựa trên giá trị bộ đếm thời gian đã chọn.</td> </tr> <tr> <td>addEventListener()</td> <td>Liên kết một sự kiện cụ thể (ví dụ: nhấp chuột) với thành phần nút. Trong ngữ cảnh này, nó được sử dụng để kích hoạt hàm ChangeTimer() khi người dùng nhấp vào nút, cho phép tương tác động với cài đặt hẹn giờ.</td> </tr> <tr> <td>innerText</td> <td>Thuộc tính này cho phép sửa đổi văn bản hiển thị trong phần tử HTML. Trong giải pháp này, nó được sử dụng để cập nhật giá trị bộ đếm thời gian trong tiêu đề của trang khi nhấp vào nút.</td> </tr> <tr> <td>onClick</td> <td>Thuộc tính xử lý sự kiện nội tuyến được sử dụng theo phương pháp thay thế để gắn trực tiếp hàm ChangeTimer() vào sự kiện nhấp chuột của nút. Điều này cho phép cập nhật bộ hẹn giờ một cách linh hoạt, đơn giản hơn, ít mô-đun hơn.</td> </tr> <tr> <td>test()</td> <td>Phương pháp này được sử dụng trong thử nghiệm đơn vị với Jest. Nó xác định một trường hợp thử nghiệm trong đó hàm đang được thử nghiệm (ví dụ: ChangeTimer()) được đánh giá để đảm bảo bộ đếm thời gian cập nhật chính xác. Nó đảm bảo mã hoạt động như mong đợi trong các tình huống khác nhau.</td> </tr> <tr> <td>expect()</td> <td>Lệnh Jest kiểm tra xem giá trị thực tế (như bộ hẹn giờ được cập nhật) có khớp với giá trị mong đợi hay không. Nó được sử dụng trong các bài kiểm tra đơn vị để xác minh rằng gameTime và document.title được cập nhật chính xác sau một lần bấm nút.</td> </tr> <tr> <td>toBe()</td> <td>Một lệnh Jest khác để kiểm tra sự bình đẳng nghiêm ngặt. Nó đảm bảo rằng sau khi gọi ChangeTimer(), thời gian trò chơi chính xác như mong đợi (ví dụ: 30.000 mili giây trong 30 giây).</td> </tr> <tr> <td>getElementById()</td> <td>Được sử dụng để chọn các nút cụ thể theo ID của chúng (ví dụ: 'ba mươi', 'sáu mươi'). Phương pháp này rất quan trọng để gắn trình xử lý sự kiện vào các nút và kích hoạt sự thay đổi động của bộ hẹn giờ để đáp ứng với tương tác của người dùng.</td> </tr></table><h3 id="dev1">Tạo bộ hẹn giờ động bằng cách sử dụng nút JavaScript và HTML</h3><div class="bordersh3"></div><p>Các tập lệnh được cung cấp ở trên được thiết kế để cho phép người dùng tự động điều chỉnh bộ hẹn giờ trò chơi trong trò chơi đánh máy bằng cách nhấp vào các nút HTML. Ban đầu chúng ta khai báo một biến <b>trò chơiThời gian</b>, giữ thời gian tính bằng mili giây (30 giây theo mặc định, nhân với 1000 để chuyển đổi thành mili giây). Chức năng chính nằm ở <b>thay đổi bộ đếm thời gian</b> chức năng cập nhật giá trị bộ đếm thời gian dựa trên nút được nhấp. Phương thức này nhận giá trị của nút (ví dụ: 30, 60 hoặc 90) và cập nhật trò chơiThời gian biến tương ứng. Ngoài ra, tập lệnh còn cập nhật tiêu đề của trang để phản ánh khoảng thời gian đã chọn, giúp người dùng biết rõ họ có bao nhiêu thời gian.</p><p>Đối với hành vi động, chúng tôi sử dụng trình xử lý sự kiện, cụ thể là <b>addEventListener</b> yêu cầu. Điều này cho phép tập lệnh phản ứng khi người dùng nhấp vào bất kỳ nút nào. Mỗi nút được gán một ID và khi được nhấp vào sẽ kích hoạt <b>thay đổi bộ đếm thời gian</b> hàm, truyền giá trị thời gian tương ứng. Cách tiếp cận này hữu ích để xử lý nhiều nút một cách hiệu quả mà không cần JavaScript nội tuyến lặp đi lặp lại trong cấu trúc HTML. Tập lệnh cũng bao gồm tùy chọn dự phòng nơi bạn có thể sử dụng các trình xử lý sự kiện nội tuyến như <b>trênClick</b> nếu sự đơn giản được ưa thích hơn tính mô-đun.</p><p>Trong giải pháp thay thế, chúng tôi liên kết trực tiếp <b>trênClick</b> sự kiện cho các nút. Phương pháp này thực hiện <b>thay đổi bộ đếm thời gian</b> hoạt động trực tiếp khi nút được nhấp vào. Đó là một cách tiếp cận đơn giản nhưng thiếu tính linh hoạt của phương thức xử lý sự kiện. Sự đơn giản của phương pháp này rất hữu ích cho các ứng dụng nhỏ hơn, ít phức tạp hơn. Tuy nhiên, để mã có khả năng mở rộng cao hơn, trình xử lý sự kiện mang lại sự linh hoạt hơn và cho phép cập nhật tập lệnh dễ dàng hơn mà không cần sửa đổi trực tiếp cấu trúc HTML. Cả hai phương pháp đều nhằm giải quyết cùng một vấn đề, đó là điều chỉnh bộ đếm thời gian và cập nhật tiêu đề một cách linh hoạt dựa trên lựa chọn của người dùng.</p><p>Cuối cùng, chúng tôi triển khai các bài kiểm tra đơn vị bằng cách sử dụng Jest, một khung kiểm tra JavaScript. các <b>Bài kiểm tra</b> các chức năng rất quan trọng để xác nhận rằng bộ hẹn giờ cập nhật đúng cách. Bằng cách kiểm tra nhiều tình huống, chẳng hạn như bộ hẹn giờ điều chỉnh thành 30 giây, 60 giây hay 90 giây, các thử nghiệm đơn vị này đảm bảo tính chính xác của tập lệnh. Các lệnh như <b>trông chờ</b> Và <b>tương lai</b> được sử dụng để xác minh rằng giá trị bộ đếm thời gian thực tế và tiêu đề trang phù hợp với kết quả mong đợi. Giai đoạn thử nghiệm này đảm bảo rằng logic hẹn giờ của bạn hoạt động bình thường trong các trường hợp sử dụng khác nhau, mang lại sự tự tin về tính mạnh mẽ của giải pháp của bạn.<div id="script0"><h3>Thay đổi giá trị bộ đếm thời gian bằng các nút HTML cho trò chơi đánh máy</h3><div class="bordersh3"></div><p class="langprog">Cách tiếp cận giao diện người dùng dựa trên JavaScript với tính năng cập nhật thời gian động và điều chỉnh tiêu đề</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>Phương pháp thay thế: Sử dụng các hàm JavaScript và HTML nội tuyến</h3><div class="bordersh3"></div><p class="langprog">JavaScript nội tuyến trong HTML với lệnh gọi hàm trực tiếp khi nhấp vào nút</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>Kiểm tra đơn vị để thay đổi giá trị bộ đếm thời gian trong các môi trường khác nhau</h3><div class="bordersh3"></div><p class="langprog">Kiểm thử đơn vị dựa trên JavaScript bằng cách sử dụng Jest để xác thực môi trường giao diện người dùng</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>Tăng cường tương tác trò chơi với tùy chỉnh hẹn giờ</h3><div class="bordersh3"></div><p>Một khía cạnh khác cần xem xét khi thay đổi bộ đếm thời gian trong trò chơi đánh máy là trải nghiệm và giao diện tổng thể của người dùng. Ngoài việc điều chỉnh bộ đếm thời gian của trò chơi thông qua các nút, điều quan trọng là cung cấp cho người chơi phản hồi trực quan về bộ đếm thời gian đã chọn của họ. Điều này có thể đạt được bằng cách cập nhật các thành phần khác trên trang, chẳng hạn như màn hình đếm ngược. Sau khi nhấp vào nút để đặt bộ hẹn giờ, đồng hồ đếm ngược sẽ bắt đầu ngay lập tức, cung cấp phản hồi theo thời gian thực cho người dùng. Điều này đảm bảo sự tương tác mượt mà và trực quan, giúp trò chơi trở nên hấp dẫn hơn.</p><p>Để thực hiện điều này, bạn có thể sử dụng JavaScript <b>tập khoảng thời gian</b> chức năng. Sau khi đã đặt hẹn giờ, tập khoảng thời gian có thể được sử dụng để tạo bộ đếm ngược làm giảm giá trị bộ đếm thời gian mỗi giây. Khi bộ đếm thời gian về 0, chức năng này có thể dừng trò chơi hoặc cảnh báo người dùng rằng đã hết thời gian. Chức năng này, kết hợp với khả năng tự động thay đổi bộ đếm thời gian bằng các nút, nâng cao đáng kể trải nghiệm chơi trò chơi. Giao diện đáp ứng là chìa khóa để thu hút người chơi và phản hồi theo thời gian thực là một cách để đạt được điều đó.</p><p>Hơn nữa, việc xử lý lỗi cũng cần được xem xét. Ví dụ: nếu người dùng cố gắng bắt đầu trò chơi mà không đặt hẹn giờ, bạn có thể nhắc họ bằng thông báo để chọn thời gian hợp lệ. Bằng cách kết hợp các cơ chế xác thực, bạn đảm bảo rằng trò chơi hoạt động trơn tru và giảm thiểu các sự cố tiềm ẩn. Loại xác thực này không chỉ cải thiện trải nghiệm người dùng mà còn góp phần nâng cao độ tin cậy cho trò chơi của bạn, đảm bảo người chơi không gặp phải sự nhầm lẫn không cần thiết.</p><div id="newfaq"><div id="adsense-article-faq"></div><h4 id="faq">Các câu hỏi thường gặp về Tùy chỉnh bộ hẹn giờ trong JavaScript</h4><div class="bordersh4"></div><ol> <li>Làm cách nào để sử dụng <strong>setInterval</strong> để tạo ra một sự đếm ngược?</li> <li>Bạn có thể sử dụng <strong>setInterval</strong> bằng cách đặt nó thực thi cứ sau 1000 mili giây (1 giây) và giảm giá trị bộ đếm thời gian mỗi lần. Khi giá trị đạt đến 0, bạn có thể dừng đếm ngược bằng cách sử dụng <strong>clearInterval</strong>.</li> <li>Mục đích của việc này là gì <strong>clearInterval</strong>?</li> <li><strong>clearInterval</strong> được sử dụng để dừng đếm ngược hoặc bất kỳ hành động định kỳ nào khác được bắt đầu bởi <strong>setInterval</strong>. Điều quan trọng là đảm bảo quá trình đếm ngược dừng lại khi nó về 0.</li> <li>Làm cách nào tôi có thể cập nhật tiêu đề HTML một cách linh hoạt?</li> <li>Sử dụng <strong>document.title</strong> để đặt văn bản của tiêu đề trang. Điều này có thể được cập nhật trong vòng của bạn <strong>changeTimer</strong> chức năng dựa trên giá trị thời gian đã chọn.</li> <li>Tôi có thể xử lý lỗi người dùng khi chọn bộ hẹn giờ không?</li> <li>Có, bạn có thể thêm xác thực bằng cách kiểm tra xem tùy chọn hẹn giờ hợp lệ đã được chọn hay chưa trước khi bắt đầu đếm ngược. Nếu không chọn thời gian hợp lệ, bạn có thể hiển thị cảnh báo hoặc lời nhắc.</li> <li>Làm cách nào để kích hoạt chức năng khi nhấp vào nút?</li> <li>Bạn có thể đính kèm một chức năng vào một nút bằng cách sử dụng <strong>addEventListener</strong> hoặc bằng cách sử dụng trực tiếp <strong>onClick</strong> trong phần tử HTML của nút.</li></ol></div><div id="summary"><h4>Suy nghĩ cuối cùng về việc tùy chỉnh bộ hẹn giờ</h4><div class="bordersh4"></div><p>Việc kết hợp các điều chỉnh hẹn giờ động trong trò chơi đánh máy sẽ cải thiện đáng kể trải nghiệm của người chơi. Bằng cách cho phép người dùng thay đổi bộ đếm thời gian bằng các nút HTML đơn giản và cập nhật giao diện của trò chơi theo thời gian thực, các nhà phát triển có thể làm cho trò chơi của họ trở nên tương tác và linh hoạt hơn. Kiểu kiểm soát này giúp đáp ứng các cấp độ kỹ năng khác nhau.</p><p>Việc sử dụng các phương pháp hay nhất như trình xử lý sự kiện, xử lý lỗi và kiểm tra đơn vị sẽ đảm bảo trò chơi chạy trơn tru và mang lại trải nghiệm đáng tin cậy cho người dùng. Việc triển khai các tính năng này sẽ không chỉ nâng cao chức năng của trò chơi mà còn giúp người chơi tương tác nhiều hơn với cơ chế phản hồi nhanh, thân thiện với người dùng.</p><div id="source"> <h6>Nguồn và tài liệu tham khảo để tùy chỉnh bộ hẹn giờ</h6> <div class="bordersh2"></div> <ol> <li>Thông tin chi tiết về cách sử dụng JavaScript để thao tác DOM và xử lý sự kiện có thể được tìm thấy trên <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide" target="_blank">Tài liệu web MDN</a> .</li> <li>Để hiểu được <a href="https://jestjs.io/docs/getting-started" target="_blank">trò đùa</a> framework và cách triển khai nó để thử nghiệm đơn vị trong các ứng dụng JavaScript.</li> <li>Những hiểu biết toàn diện về việc sử dụng <a href="https://www.w3schools.com/js/js_htmldom_eventlistener.asp" target="_blank">addEventListener</a> để xử lý các sự kiện trong JavaScript có sẵn trên W3Schools.</li> <li>Tầm quan trọng của việc cập nhật theo thời gian thực trong các ứng dụng web, bao gồm cả bộ tính giờ, sẽ được thảo luận trong <a href="https://www.smashingmagazine.com/2020/02/real-time-app-web/" target="_blank">tạp chí đập phá</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">Bạn đang tìm kiếm thư tạm thời ẩn danh hoạt động tốt nhất trên Internet? Dịch vụ e-mail tạm thời miễn phí của chúng tôi là dịch vụ hoàn chỉnh nhất, Nhận và gửi e-mail, Tạo chuyển hướng đến các e-mail yêu thích của bạn. Giữ mật khẩu của bạn và sử dụng email tạm thời của bạn suốt đời. POP3, IMAP và SMTP có sẵn miễn phí.</p> <div style="width:100%;text-align:right;"> <a class="read-more--with-arrow" href="https://www.tempmail.us.com/vi/"> 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 = "Sao chép và dán"; 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,"Nội dung được sao chép vào clipboard!","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: 'vi', addQueryCat: "AND catclean='javascript'", page: page, currentid: "100108", 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/nh%E1%BB%AFng-thach-th%E1%BB%A9c-khi-th%E1%BB%B1c-hi%E1%BB%87n-cac-quy-trinh-l%C6%B0u-tr%E1%BB%AF-d%E1%BB%B1a-tren-javascript-trong-snowflake-thong-qua-dag-lu%E1%BB%93ng-khi.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/vi/snowflake/nh%E1%BB%AFng-thach-th%E1%BB%A9c-khi-th%E1%BB%B1c-hi%E1%BB%87n-cac-quy-trinh-l%C6%B0u-tr%E1%BB%AF-d%E1%BB%B1a-tren-javascript-trong-snowflake-thong-qua-dag-lu%E1%BB%93ng-khi'); // Charger la page suivante chargerPageSuivante('https://www.tempmail.us.com/vi/snowflake/nh%E1%BB%AFng-thach-th%E1%BB%A9c-khi-th%E1%BB%B1c-hi%E1%BB%87n-cac-quy-trinh-l%C6%B0u-tr%E1%BB%AF-d%E1%BB%B1a-tren-javascript-trong-snowflake-thong-qua-dag-lu%E1%BB%93ng-khi'); // 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; } // 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/cach-s%E1%BB%ADa-d%E1%BB%95i-gia-tr%E1%BB%8B-b%E1%BB%99-d%E1%BA%BFm-th%E1%BB%9Di-gian-javascript-cho-tro-ch%C6%A1i-danh-may-b%E1%BA%B1ng-cac-nut-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>