#jquery foreach function
Explore tagged Tumblr posts
w3bcombr · 1 year ago
Text
Quando comecei a codificar em JavaScript em 2013, pensei que jQuery era o “JavaScript” real e que jQuery deveria ser incluído em todas as páginas para executar meu código JS. Caros desenvolvedores de plug-ins Mas por que? Porque todo código que copiei do StackOverflow funcionou somente após importar o jQuery! 😅 O que há de errado com jQuery jQuery tem 90 KB, mas quando reduzido tem apenas 32 KB. Isso é tão pequeno. Um bom CDN pode entregar isso em menos de 50ms! Mas não se trata do tamanho. jQuery tem cerca de 10 mil linhas de código. Você pode não estar usando nem 10% dele. Cada linha deve ser analisada e avaliada pelo navegador, o que consome muitos recursos. Este processo afeta o tempo de renderização, especialmente em dispositivos móveis. Para ver a diferença real, aqui está a mesma funcionalidade escrita em jQuery puro e JavaScript vanilla: jQuery: // jQuery const div = $("#hello-div"); for (let i = 0; i < 10000; i += 1) div.append(" Hello world "); JavaScript baunilha: // Pure JavaScript const div = document.getElementById("hello-div"); for (let i = 0; i < 10000; i += 1) const p = document.createElement("p"); p.textContent = "Hello world"; div.appendChild(p); Aqui está a diferença de desempenho: Enquanto jQuery levou 2,4s, JavaScript puro levou apenas 0,8s. Isso mostra Vanilla JavaScript é 4x mais rápido que jQuery. Alguns anos atrás, escrever funções padrão em JavaScript vanilla era uma dor e o jQuery tornou nossas vidas mais fáceis. Mas os navegadores da web evoluíram muito. A maioria das funções que você escreveu em jQuery podem ser escritas em JavaScript puro. Aqui estão alguns exemplos: 1. Solicitações Ajax Buscando dados de um URL: jQuery: $.ajax( url: '/api.json', type: 'GET' success: (data) => console.log(data) ) JavaScript baunilha: fetch('/api.json') .then(response => response.text()) .then(body => console.log(body)) 2. Encontre elementos e manipule Encontre alguns elementos do DOM (HTML) e mude de cor: jQuery: Olácomo vai você? Meu? Eu sou bom. $("p").find("span").css("color", "red"); JavaScript baunilha: Olácomo vai você? Meu? Eu sou bom. document .querySelectorAll("p > span") .forEach((elem) => (elem.style.color = "red")); 3. Mostrar/ocultar elementos Caso de uso comum de jQuery, mostrar/ocultar algo ao clicar: jQuery: Me esconda $("#button").click(function () $("#button").hide(); ); JavaScript baunilha: Me esconda document.getElementById("button").addEventListener("click", function () document.getElementById("button").style.display = "none"; ); 4. Animar jQuery: Me esconda $("#button").click(function () $("#button").hide("slow"); ); JavaScript baunilha: .animate opacidade: 0; transição: opacidade 0,5s de facilidade; Me esconda document.getElementById("button").addEventListener("click", function () document.getElementById("button").classList.add("animate"); ); Você pode encontrar muito mais exemplos semelhantes em: Você pode não precisar do jQuery Você deve usar ou aprender jQuery em 2020? Do jQuery ao JavaScript – Como fazer a mudança E quanto ao suporte ao navegador? A maioria das funções que usei acima são amplamente suportadas em todos os principais navegadores. Caros desenvolvedores de plug-insCaros desenvolvedores de plug-ins Geralmente é o Internet Explorer e o Opera Mini, que não suportam alguns deles. Se ainda quiser oferecer suporte a esses navegadores antigos, você pode detectar o navegador e adicionar polyfills. Aqui estão alguns polyfills para essas funções comuns: github/eventlistener-polyfill github/buscar iamdustan/smoothscroll yola/classlist-polyfill Suporte do navegador para querySelector: Suporte do navegador para fetch: Todo mundo está se mudando, exceto WordPress Graças ao avanço feito nas ferramentas de desenvolvimento front-end e no suporte do navegador,
agora podemos descartar o jQuery como uma dependência, mas você nunca notaria o contrário Caros desenvolvedores de plug-ins Bootstrap 5 – postagem no blog GitHub.com também removeu o jQuery em 2018 – Removendo jQuery do front-end do GitHub.com. Embora todos tenham começado a se afastar do jQuery, é bastante complicado no WordPress devido ao grande número de plug-ins e temas. Da recente postagem no blog de Atualizando a versão do jQuery fornecida com o WordPress: O WordPress deve descontinuar o jQuery e migrar gradualmente para o Vanilla JavaScript. Talvez você também não precise de JavaScript Caros desenvolvedores de plug-ins Como eu disse antes, a web e o JavaScript estão evoluindo rapidamente. Da mesma forma CSS. Muitas funções que eram feitas via JavaScript agora são feitas via CSS. Isso proporciona outro aumento de desempenho. Caros desenvolvedores de plug-ins Algumas delas que podem ser feitas em CSS puro: Controle deslizante de imagem – Construtor de controle deslizante CSS, Galeria CSS, Controle deslizante CSS puro Modal – Modal CSS Puro Validação de formulário – Validação de formulário HTML Indicador de rolagem – Indicador de rolagem somente CSS Acordeão – 4 maneiras de criar acordeões incríveis somente com CSS Caixa de luz – Caixa de luz CSS pura, Caixa de luz somente CSS Guias – Guias somente CSS, Guias somente CSS do Material Design Role para cima - Puro CSS Smooth-Scroll “Voltar ao topo” Rolagem suave para links – Demonstração de rolagem suave CSS Barra de navegação fixa – Cabeçalho fixo CSS puro Caros desenvolvedores de plug-ins
0 notes
vilaoperaria · 1 year ago
Text
Quando comecei a codificar em JavaScript em 2013, pensei que jQuery era o “JavaScript” real e que jQuery deveria ser incluído em todas as páginas para executar meu código JS. Caros desenvolvedores de plug-ins Mas por que? Porque todo código que copiei do StackOverflow funcionou somente após importar o jQuery! 😅 O que há de errado com jQuery jQuery tem 90 KB, mas quando reduzido tem apenas 32 KB. Isso é tão pequeno. Um bom CDN pode entregar isso em menos de 50ms! Mas não se trata do tamanho. jQuery tem cerca de 10 mil linhas de código. Você pode não estar usando nem 10% dele. Cada linha deve ser analisada e avaliada pelo navegador, o que consome muitos recursos. Este processo afeta o tempo de renderização, especialmente em dispositivos móveis. Para ver a diferença real, aqui está a mesma funcionalidade escrita em jQuery puro e JavaScript vanilla: jQuery: // jQuery const div = $("#hello-div"); for (let i = 0; i < 10000; i += 1) div.append(" Hello world "); JavaScript baunilha: // Pure JavaScript const div = document.getElementById("hello-div"); for (let i = 0; i < 10000; i += 1) const p = document.createElement("p"); p.textContent = "Hello world"; div.appendChild(p); Aqui está a diferença de desempenho: Enquanto jQuery levou 2,4s, JavaScript puro levou apenas 0,8s. Isso mostra Vanilla JavaScript é 4x mais rápido que jQuery. Alguns anos atrás, escrever funções padrão em JavaScript vanilla era uma dor e o jQuery tornou nossas vidas mais fáceis. Mas os navegadores da web evoluíram muito. A maioria das funções que você escreveu em jQuery podem ser escritas em JavaScript puro. Aqui estão alguns exemplos: 1. Solicitações Ajax Buscando dados de um URL: jQuery: $.ajax( url: '/api.json', type: 'GET' success: (data) => console.log(data) ) JavaScript baunilha: fetch('/api.json') .then(response => response.text()) .then(body => console.log(body)) 2. Encontre elementos e manipule Encontre alguns elementos do DOM (HTML) e mude de cor: jQuery: Olácomo vai você? Meu? Eu sou bom. $("p").find("span").css("color", "red"); JavaScript baunilha: Olácomo vai você? Meu? Eu sou bom. document .querySelectorAll("p > span") .forEach((elem) => (elem.style.color = "red")); 3. Mostrar/ocultar elementos Caso de uso comum de jQuery, mostrar/ocultar algo ao clicar: jQuery: Me esconda $("#button").click(function () $("#button").hide(); ); JavaScript baunilha: Me esconda document.getElementById("button").addEventListener("click", function () document.getElementById("button").style.display = "none"; ); 4. Animar jQuery: Me esconda $("#button").click(function () $("#button").hide("slow"); ); JavaScript baunilha: .animate opacidade: 0; transição: opacidade 0,5s de facilidade; Me esconda document.getElementById("button").addEventListener("click", function () document.getElementById("button").classList.add("animate"); ); Você pode encontrar muito mais exemplos semelhantes em: Você pode não precisar do jQuery Você deve usar ou aprender jQuery em 2020? Do jQuery ao JavaScript – Como fazer a mudança E quanto ao suporte ao navegador? A maioria das funções que usei acima são amplamente suportadas em todos os principais navegadores. Caros desenvolvedores de plug-insCaros desenvolvedores de plug-ins Geralmente é o Internet Explorer e o Opera Mini, que não suportam alguns deles. Se ainda quiser oferecer suporte a esses navegadores antigos, você pode detectar o navegador e adicionar polyfills. Aqui estão alguns polyfills para essas funções comuns: github/eventlistener-polyfill github/buscar iamdustan/smoothscroll yola/classlist-polyfill Suporte do navegador para querySelector: Suporte do navegador para fetch: Todo mundo está se mudando, exceto WordPress Graças ao avanço feito nas ferramentas de desenvolvimento front-end e no suporte do navegador,
agora podemos descartar o jQuery como uma dependência, mas você nunca notaria o contrário Caros desenvolvedores de plug-ins Bootstrap 5 – postagem no blog GitHub.com também removeu o jQuery em 2018 – Removendo jQuery do front-end do GitHub.com. Embora todos tenham começado a se afastar do jQuery, é bastante complicado no WordPress devido ao grande número de plug-ins e temas. Da recente postagem no blog de Atualizando a versão do jQuery fornecida com o WordPress: O WordPress deve descontinuar o jQuery e migrar gradualmente para o Vanilla JavaScript. Talvez você também não precise de JavaScript Caros desenvolvedores de plug-ins Como eu disse antes, a web e o JavaScript estão evoluindo rapidamente. Da mesma forma CSS. Muitas funções que eram feitas via JavaScript agora são feitas via CSS. Isso proporciona outro aumento de desempenho. Caros desenvolvedores de plug-ins Algumas delas que podem ser feitas em CSS puro: Controle deslizante de imagem – Construtor de controle deslizante CSS, Galeria CSS, Controle deslizante CSS puro Modal – Modal CSS Puro Validação de formulário – Validação de formulário HTML Indicador de rolagem – Indicador de rolagem somente CSS Acordeão – 4 maneiras de criar acordeões incríveis somente com CSS Caixa de luz – Caixa de luz CSS pura, Caixa de luz somente CSS Guias – Guias somente CSS, Guias somente CSS do Material Design Role para cima - Puro CSS Smooth-Scroll “Voltar ao topo” Rolagem suave para links – Demonstração de rolagem suave CSS Barra de navegação fixa – Cabeçalho fixo CSS puro Caros desenvolvedores de plug-ins
0 notes
mirandascontalidade · 1 year ago
Text
Quando comecei a codificar em JavaScript em 2013, pensei que jQuery era o “JavaScript” real e que jQuery deveria ser incluído em todas as páginas para executar meu código JS. Caros desenvolvedores de plug-ins Mas por que? Porque todo código que copiei do StackOverflow funcionou somente após importar o jQuery! 😅 O que há de errado com jQuery jQuery tem 90 KB, mas quando reduzido tem apenas 32 KB. Isso é tão pequeno. Um bom CDN pode entregar isso em menos de 50ms! Mas não se trata do tamanho. jQuery tem cerca de 10 mil linhas de código. Você pode não estar usando nem 10% dele. Cada linha deve ser analisada e avaliada pelo navegador, o que consome muitos recursos. Este processo afeta o tempo de renderização, especialmente em dispositivos móveis. Para ver a diferença real, aqui está a mesma funcionalidade escrita em jQuery puro e JavaScript vanilla: jQuery: // jQuery const div = $("#hello-div"); for (let i = 0; i < 10000; i += 1) div.append(" Hello world "); JavaScript baunilha: // Pure JavaScript const div = document.getElementById("hello-div"); for (let i = 0; i < 10000; i += 1) const p = document.createElement("p"); p.textContent = "Hello world"; div.appendChild(p); Aqui está a diferença de desempenho: Enquanto jQuery levou 2,4s, JavaScript puro levou apenas 0,8s. Isso mostra Vanilla JavaScript é 4x mais rápido que jQuery. Alguns anos atrás, escrever funções padrão em JavaScript vanilla era uma dor e o jQuery tornou nossas vidas mais fáceis. Mas os navegadores da web evoluíram muito. A maioria das funções que você escreveu em jQuery podem ser escritas em JavaScript puro. Aqui estão alguns exemplos: 1. Solicitações Ajax Buscando dados de um URL: jQuery: $.ajax( url: '/api.json', type: 'GET' success: (data) => console.log(data) ) JavaScript baunilha: fetch('/api.json') .then(response => response.text()) .then(body => console.log(body)) 2. Encontre elementos e manipule Encontre alguns elementos do DOM (HTML) e mude de cor: jQuery: Olácomo vai você? Meu? Eu sou bom. $("p").find("span").css("color", "red"); JavaScript baunilha: Olácomo vai você? Meu? Eu sou bom. document .querySelectorAll("p > span") .forEach((elem) => (elem.style.color = "red")); 3. Mostrar/ocultar elementos Caso de uso comum de jQuery, mostrar/ocultar algo ao clicar: jQuery: Me esconda $("#button").click(function () $("#button").hide(); ); JavaScript baunilha: Me esconda document.getElementById("button").addEventListener("click", function () document.getElementById("button").style.display = "none"; ); 4. Animar jQuery: Me esconda $("#button").click(function () $("#button").hide("slow"); ); JavaScript baunilha: .animate opacidade: 0; transição: opacidade 0,5s de facilidade; Me esconda document.getElementById("button").addEventListener("click", function () document.getElementById("button").classList.add("animate"); ); Você pode encontrar muito mais exemplos semelhantes em: Você pode não precisar do jQuery Você deve usar ou aprender jQuery em 2020? Do jQuery ao JavaScript – Como fazer a mudança E quanto ao suporte ao navegador? A maioria das funções que usei acima são amplamente suportadas em todos os principais navegadores. Caros desenvolvedores de plug-insCaros desenvolvedores de plug-ins Geralmente é o Internet Explorer e o Opera Mini, que não suportam alguns deles. Se ainda quiser oferecer suporte a esses navegadores antigos, você pode detectar o navegador e adicionar polyfills. Aqui estão alguns polyfills para essas funções comuns: github/eventlistener-polyfill github/buscar iamdustan/smoothscroll yola/classlist-polyfill Suporte do navegador para querySelector: Suporte do navegador para fetch: Todo mundo está se mudando, exceto WordPress Graças ao avanço feito nas ferramentas de desenvolvimento front-end e no suporte do navegador,
agora podemos descartar o jQuery como uma dependência, mas você nunca notaria o contrário Caros desenvolvedores de plug-ins Bootstrap 5 – postagem no blog GitHub.com também removeu o jQuery em 2018 – Removendo jQuery do front-end do GitHub.com. Embora todos tenham começado a se afastar do jQuery, é bastante complicado no WordPress devido ao grande número de plug-ins e temas. Da recente postagem no blog de Atualizando a versão do jQuery fornecida com o WordPress: O WordPress deve descontinuar o jQuery e migrar gradualmente para o Vanilla JavaScript. Talvez você também não precise de JavaScript Caros desenvolvedores de plug-ins Como eu disse antes, a web e o JavaScript estão evoluindo rapidamente. Da mesma forma CSS. Muitas funções que eram feitas via JavaScript agora são feitas via CSS. Isso proporciona outro aumento de desempenho. Caros desenvolvedores de plug-ins Algumas delas que podem ser feitas em CSS puro: Controle deslizante de imagem – Construtor de controle deslizante CSS, Galeria CSS, Controle deslizante CSS puro Modal – Modal CSS Puro Validação de formulário – Validação de formulário HTML Indicador de rolagem – Indicador de rolagem somente CSS Acordeão – 4 maneiras de criar acordeões incríveis somente com CSS Caixa de luz – Caixa de luz CSS pura, Caixa de luz somente CSS Guias – Guias somente CSS, Guias somente CSS do Material Design Role para cima - Puro CSS Smooth-Scroll “Voltar ao topo” Rolagem suave para links – Demonstração de rolagem suave CSS Barra de navegação fixa – Cabeçalho fixo CSS puro Caros desenvolvedores de plug-ins
0 notes
internacoesvidanova · 1 year ago
Text
Quando comecei a codificar em JavaScript em 2013, pensei que jQuery era o “JavaScript” real e que jQuery deveria ser incluído em todas as páginas para executar meu código JS. Caros desenvolvedores de plug-ins Mas por que? Porque todo código que copiei do StackOverflow funcionou somente após importar o jQuery! 😅 O que há de errado com jQuery jQuery tem 90 KB, mas quando reduzido tem apenas 32 KB. Isso é tão pequeno. Um bom CDN pode entregar isso em menos de 50ms! Mas não se trata do tamanho. jQuery tem cerca de 10 mil linhas de código. Você pode não estar usando nem 10% dele. Cada linha deve ser analisada e avaliada pelo navegador, o que consome muitos recursos. Este processo afeta o tempo de renderização, especialmente em dispositivos móveis. Para ver a diferença real, aqui está a mesma funcionalidade escrita em jQuery puro e JavaScript vanilla: jQuery: // jQuery const div = $("#hello-div"); for (let i = 0; i < 10000; i += 1) div.append(" Hello world "); JavaScript baunilha: // Pure JavaScript const div = document.getElementById("hello-div"); for (let i = 0; i < 10000; i += 1) const p = document.createElement("p"); p.textContent = "Hello world"; div.appendChild(p); Aqui está a diferença de desempenho: Enquanto jQuery levou 2,4s, JavaScript puro levou apenas 0,8s. Isso mostra Vanilla JavaScript é 4x mais rápido que jQuery. Alguns anos atrás, escrever funções padrão em JavaScript vanilla era uma dor e o jQuery tornou nossas vidas mais fáceis. Mas os navegadores da web evoluíram muito. A maioria das funções que você escreveu em jQuery podem ser escritas em JavaScript puro. Aqui estão alguns exemplos: 1. Solicitações Ajax Buscando dados de um URL: jQuery: $.ajax( url: '/api.json', type: 'GET' success: (data) => console.log(data) ) JavaScript baunilha: fetch('/api.json') .then(response => response.text()) .then(body => console.log(body)) 2. Encontre elementos e manipule Encontre alguns elementos do DOM (HTML) e mude de cor: jQuery: Olácomo vai você? Meu? Eu sou bom. $("p").find("span").css("color", "red"); JavaScript baunilha: Olácomo vai você? Meu? Eu sou bom. document .querySelectorAll("p > span") .forEach((elem) => (elem.style.color = "red")); 3. Mostrar/ocultar elementos Caso de uso comum de jQuery, mostrar/ocultar algo ao clicar: jQuery: Me esconda $("#button").click(function () $("#button").hide(); ); JavaScript baunilha: Me esconda document.getElementById("button").addEventListener("click", function () document.getElementById("button").style.display = "none"; ); 4. Animar jQuery: Me esconda $("#button").click(function () $("#button").hide("slow"); ); JavaScript baunilha: .animate opacidade: 0; transição: opacidade 0,5s de facilidade; Me esconda document.getElementById("button").addEventListener("click", function () document.getElementById("button").classList.add("animate"); ); Você pode encontrar muito mais exemplos semelhantes em: Você pode não precisar do jQuery Você deve usar ou aprender jQuery em 2020? Do jQuery ao JavaScript – Como fazer a mudança E quanto ao suporte ao navegador? A maioria das funções que usei acima são amplamente suportadas em todos os principais navegadores. Caros desenvolvedores de plug-insCaros desenvolvedores de plug-ins Geralmente é o Internet Explorer e o Opera Mini, que não suportam alguns deles. Se ainda quiser oferecer suporte a esses navegadores antigos, você pode detectar o navegador e adicionar polyfills. Aqui estão alguns polyfills para essas funções comuns: github/eventlistener-polyfill github/buscar iamdustan/smoothscroll yola/classlist-polyfill Suporte do navegador para querySelector: Suporte do navegador para fetch: Todo mundo está se mudando, exceto WordPress Graças ao avanço feito nas ferramentas de desenvolvimento front-end e no suporte do navegador,
agora podemos descartar o jQuery como uma dependência, mas você nunca notaria o contrário Caros desenvolvedores de plug-ins Bootstrap 5 – postagem no blog GitHub.com também removeu o jQuery em 2018 – Removendo jQuery do front-end do GitHub.com. Embora todos tenham começado a se afastar do jQuery, é bastante complicado no WordPress devido ao grande número de plug-ins e temas. Da recente postagem no blog de Atualizando a versão do jQuery fornecida com o WordPress: O WordPress deve descontinuar o jQuery e migrar gradualmente para o Vanilla JavaScript. Talvez você também não precise de JavaScript Caros desenvolvedores de plug-ins Como eu disse antes, a web e o JavaScript estão evoluindo rapidamente. Da mesma forma CSS. Muitas funções que eram feitas via JavaScript agora são feitas via CSS. Isso proporciona outro aumento de desempenho. Caros desenvolvedores de plug-ins Algumas delas que podem ser feitas em CSS puro: Controle deslizante de imagem – Construtor de controle deslizante CSS, Galeria CSS, Controle deslizante CSS puro Modal – Modal CSS Puro Validação de formulário – Validação de formulário HTML Indicador de rolagem – Indicador de rolagem somente CSS Acordeão – 4 maneiras de criar acordeões incríveis somente com CSS Caixa de luz – Caixa de luz CSS pura, Caixa de luz somente CSS Guias – Guias somente CSS, Guias somente CSS do Material Design Role para cima - Puro CSS Smooth-Scroll “Voltar ao topo” Rolagem suave para links – Demonstração de rolagem suave CSS Barra de navegação fixa – Cabeçalho fixo CSS puro Caros desenvolvedores de plug-ins
0 notes
gwsnet · 1 year ago
Text
Quando comecei a codificar em JavaScript em 2013, pensei que jQuery era o “JavaScript” real e que jQuery deveria ser incluído em todas as páginas para executar meu código JS. Caros desenvolvedores de plug-ins Mas por que? Porque todo código que copiei do StackOverflow funcionou somente após importar o jQuery! 😅 O que há de errado com jQuery jQuery tem 90 KB, mas quando reduzido tem apenas 32 KB. Isso é tão pequeno. Um bom CDN pode entregar isso em menos de 50ms! Mas não se trata do tamanho. jQuery tem cerca de 10 mil linhas de código. Você pode não estar usando nem 10% dele. Cada linha deve ser analisada e avaliada pelo navegador, o que consome muitos recursos. Este processo afeta o tempo de renderização, especialmente em dispositivos móveis. Para ver a diferença real, aqui está a mesma funcionalidade escrita em jQuery puro e JavaScript vanilla: jQuery: // jQuery const div = $("#hello-div"); for (let i = 0; i < 10000; i += 1) div.append(" Hello world "); JavaScript baunilha: // Pure JavaScript const div = document.getElementById("hello-div"); for (let i = 0; i < 10000; i += 1) const p = document.createElement("p"); p.textContent = "Hello world"; div.appendChild(p); Aqui está a diferença de desempenho: Enquanto jQuery levou 2,4s, JavaScript puro levou apenas 0,8s. Isso mostra Vanilla JavaScript é 4x mais rápido que jQuery. Alguns anos atrás, escrever funções padrão em JavaScript vanilla era uma dor e o jQuery tornou nossas vidas mais fáceis. Mas os navegadores da web evoluíram muito. A maioria das funções que você escreveu em jQuery podem ser escritas em JavaScript puro. Aqui estão alguns exemplos: 1. Solicitações Ajax Buscando dados de um URL: jQuery: $.ajax( url: '/api.json', type: 'GET' success: (data) => console.log(data) ) JavaScript baunilha: fetch('/api.json') .then(response => response.text()) .then(body => console.log(body)) 2. Encontre elementos e manipule Encontre alguns elementos do DOM (HTML) e mude de cor: jQuery: Olácomo vai você? Meu? Eu sou bom. $("p").find("span").css("color", "red"); JavaScript baunilha: Olácomo vai você? Meu? Eu sou bom. document .querySelectorAll("p > span") .forEach((elem) => (elem.style.color = "red")); 3. Mostrar/ocultar elementos Caso de uso comum de jQuery, mostrar/ocultar algo ao clicar: jQuery: Me esconda $("#button").click(function () $("#button").hide(); ); JavaScript baunilha: Me esconda document.getElementById("button").addEventListener("click", function () document.getElementById("button").style.display = "none"; ); 4. Animar jQuery: Me esconda $("#button").click(function () $("#button").hide("slow"); ); JavaScript baunilha: .animate opacidade: 0; transição: opacidade 0,5s de facilidade; Me esconda document.getElementById("button").addEventListener("click", function () document.getElementById("button").classList.add("animate"); ); Você pode encontrar muito mais exemplos semelhantes em: Você pode não precisar do jQuery Você deve usar ou aprender jQuery em 2020? Do jQuery ao JavaScript – Como fazer a mudança E quanto ao suporte ao navegador? A maioria das funções que usei acima são amplamente suportadas em todos os principais navegadores. Caros desenvolvedores de plug-insCaros desenvolvedores de plug-ins Geralmente é o Internet Explorer e o Opera Mini, que não suportam alguns deles. Se ainda quiser oferecer suporte a esses navegadores antigos, você pode detectar o navegador e adicionar polyfills. Aqui estão alguns polyfills para essas funções comuns: github/eventlistener-polyfill github/buscar iamdustan/smoothscroll yola/classlist-polyfill Suporte do navegador para querySelector: Suporte do navegador para fetch: Todo mundo está se mudando, exceto WordPress Graças ao avanço feito nas ferramentas de desenvolvimento front-end e no suporte do navegador,
agora podemos descartar o jQuery como uma dependência, mas você nunca notaria o contrário Caros desenvolvedores de plug-ins Bootstrap 5 – postagem no blog GitHub.com também removeu o jQuery em 2018 – Removendo jQuery do front-end do GitHub.com. Embora todos tenham começado a se afastar do jQuery, é bastante complicado no WordPress devido ao grande número de plug-ins e temas. Da recente postagem no blog de Atualizando a versão do jQuery fornecida com o WordPress: O WordPress deve descontinuar o jQuery e migrar gradualmente para o Vanilla JavaScript. Talvez você também não precise de JavaScript Caros desenvolvedores de plug-ins Como eu disse antes, a web e o JavaScript estão evoluindo rapidamente. Da mesma forma CSS. Muitas funções que eram feitas via JavaScript agora são feitas via CSS. Isso proporciona outro aumento de desempenho. Caros desenvolvedores de plug-ins Algumas delas que podem ser feitas em CSS puro: Controle deslizante de imagem – Construtor de controle deslizante CSS, Galeria CSS, Controle deslizante CSS puro Modal – Modal CSS Puro Validação de formulário – Validação de formulário HTML Indicador de rolagem – Indicador de rolagem somente CSS Acordeão – 4 maneiras de criar acordeões incríveis somente com CSS Caixa de luz – Caixa de luz CSS pura, Caixa de luz somente CSS Guias – Guias somente CSS, Guias somente CSS do Material Design Role para cima - Puro CSS Smooth-Scroll “Voltar ao topo” Rolagem suave para links – Demonstração de rolagem suave CSS Barra de navegação fixa – Cabeçalho fixo CSS puro Caros desenvolvedores de plug-ins
0 notes
eazy-group · 2 years ago
Text
The 8 Best Treadmills for Home of 2023
New Post has been published on https://eazyfitness.net/the-8-best-treadmills-for-home-of-2023/
The 8 Best Treadmills for Home of 2023
Tumblr media
[] The 8 Best Treadmills for Home of 2023 | Breaking Muscle
0);var b=document.getElementsByTagName(“body”)[0];var config=childList:!0,subtree:!0;observer.observe(b,config),!1)]]>=0?”perfmatters-“+r:re[t]function r(e,t)let r=e[t];Object.defineProperty(e,t,get:r)t(document,”DOMContentLoaded”),t(window,”DOMContentLoaded”),t(window,”load”),t(window,”pageshow”),t(document,”readystatechange”),r(document,”onreadystatechange”),r(window,”onload”),r(window,”onpageshow”)}function pmDelayJQueryReady()let e=window.jQuery;Object.defineProperty(window,”jQuery”,get:()=>e,set(t)if(t&&t.fn&&!jQueriesArray.includes(t))t.fn.ready=t.fn.init.prototype.ready=function(e)pmDOMLoaded?e.bind(document)(t):document.addEventListener(“perfmatters-DOMContentLoaded”,function()e.bind(document)(t));let r=t.fn.on;t.fn.on=t.fn.init.prototype.on=function()if(this[0]===window)function e(e)return e=(e=(e=e.split(” “)).map(function(e)return”load”===e)).join(” “)”string”==typeof arguments[0]return r.apply(this,arguments),this,jQueriesArray.push(t)e=t)function pmProcessDocumentWrite()let e=new Map;document.write=document.writeln=function(t)var r=document.currentScript,n=document.createRange();let a=e.get(r);void 0===a&&(a=r.nextSibling,e.set(r,a));var i=document.createDocumentFragment();n.setStart(i,0),i.appendChild(n.createContextualFragment(t)),r.parentElement.insertBefore(i,a)function pmSortDelayedScripts()document.querySelectorAll(“script[type=pmdelayedscript]”).forEach(function(e)e.hasAttribute(“src”)?e.hasAttribute(“defer”)&&!1!==e.defer?pmDelayedScripts.defer.push(e):e.hasAttribute(“async”)&&!1!==e.async?pmDelayedScripts.async.push(e):pmDelayedScripts.normal.push(e):pmDelayedScripts.normal.push(e))function pmPreloadDelayedScripts()var e=document.createDocumentFragment();[…pmDelayedScripts.normal,…pmDelayedScripts.defer,…pmDelayedScripts.async].forEach(function(t)var r=t.getAttribute(“src”);if(r)var n=document.createElement(“link”);n.href=r,n.rel=”preload”,n.as=”script”,e.appendChild(n)),document.head.appendChild(e)async function pmLoadDelayedScripts(e)var t=e.shift();return t?(await pmReplaceScript(t),pmLoadDelayedScripts(e)):Promise.resolve()async function pmReplaceScript(e)return await pmNextFrame(),new Promise(function(t)let r=document.createElement(“script”);[…e.attributes].forEach(function(e)let t=e.nodeName;”type”!==t&&(“data-type”===t&&(t=”type”),r.setAttribute(t,e.nodeValue))),e.hasAttribute(“src”)?(r.addEventListener(“load”,t),r.addEventListener(“error”,t)):(r.text=e.text,t()),e.parentNode.replaceChild(r,e))async function pmTriggerEventListeners()pmDOMLoaded=!0,await pmNextFrame(),document.dispatchEvent(new Event(“perfmatters-DOMContentLoaded”)),await pmNextFrame(),window.dispatchEvent(new Event(“perfmatters-DOMContentLoaded”)),await pmNextFrame(),document.dispatchEvent(new Event(“perfmatters-readystatechange”)),await pmNextFrame(),document.perfmattersonreadystatechange&&document.perfmattersonreadystatechange(),await pmNextFrame(),window.dispatchEvent(new Event(“perfmatters-load”)),await pmNextFrame(),window.perfmattersonload&&window.perfmattersonload(),await pmNextFrame(),jQueriesArray.forEach(function(e)e(window).trigger(“perfmatters-jquery-load”));let e=new Event(“perfmatters-pageshow”);e.persisted=window.pmPersisted,window.dispatchEvent(e),await pmNextFrame(),window.perfmattersonpageshow&&window.perfmattersonpageshow(persisted:window.pmPersisted)async function pmNextFrame()return new Promise(function(e)requestAnimationFrame(e))function pmClickHandler(e)e.target.removeEventListener(“click”,pmClickHandler),pmRenameDOMAttribute(e.target,”pm-onclick”,”onclick”),pmInterceptedClicks.push(e),e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()function pmReplayClicks()window.removeEventListener(“touchstart”,pmTouchStartHandler,passive:!0),window.removeEventListener(“mousedown”,pmTouchStartHandler),pmInterceptedClicks.forEach(e=>e.target.outerHTML===pmClickTarget&&e.target.dispatchEvent(new MouseEvent(“click”,view:e.view,bubbles:!0,cancelable:!0)))function pmTouchStartHandler(e)“HTML”!==e.target.tagName&&(pmClickTargetfunction pmTouchMoveHandler(e)window.removeEventListener(“touchend”,pmTouchEndHandler),window.removeEventListener(“mouseup”,pmTouchEndHandler),window.removeEventListener(“touchmove”,pmTouchMoveHandler,passive:!0),window.removeEventListener(“mousemove”,pmTouchMoveHandler),e.target.removeEventListener(“click”,pmClickHandler),pmRenameDOMAttribute(e.target,”pm-onclick”,”onclick”)function pmTouchEndHandler(e)window.removeEventListener(“touchend”,pmTouchEndHandler),window.removeEventListener(“mouseup”,pmTouchEndHandler),window.removeEventListener(“touchmove”,pmTouchMoveHandler,passive:!0),window.removeEventListener(“mousemove”,pmTouchMoveHandler)function pmRenameDOMAttribute(e,t,r)e.hasAttribute&&e.hasAttribute(t)&&(event.target.setAttribute(r,event.target.getAttribute(t)),event.target.removeAttribute(t))window.addEventListener(“pageshow”,e=>window.pmPersisted=e.persisted),pmUserInteractions.forEach(function(e)window.addEventListener(e,pmTriggerDOMListener,passive:!0)),pmDelayClick&&(window.addEventListener(“touchstart”,pmTouchStartHandler,passive:!0),window.addEventListener(“mousedown”,pmTouchStartHandler)),document.addEventListener(“visibilitychange”,pmTriggerDOMListener);]]> Source
0 notes
codetriks · 5 years ago
Text
Jquery JTemplate
Tumblr media
Jquery JTemplate
Hi I have written and developed this site so that students may learn computer science related technologies easily. I am committed to provide easy and in depth tutorials on various technologies. No one is perfect in this world and nothing is impossible. I give my best for you. I hope it will help you….Thanks
Codetriks is an educational website which is provide  IT Tutorial .
In IT we provide Jquery JTemplate Tutorial for beginners so learn Jquery JTemplate  and increase your knowledge with us.
Codetriks provide IT tutorials – Jquery AJAX ,Jquery Basic,Jquery Selectors,Curd Operation using Jquery,Insert using jquery,Update using Jquery,Delete using jquery,Jquery grid,Jquery JTemplate,check uncheck checkbox using jquery,jquery onclick events,jquery Insert update delete code,jquery table ,jquery css,jquery foreach function,jquery tutorial,jquery sample demo,jquery examples
Our  website provide codes for every technology so please use this website. And also give me feedback how you feel.
Codetriks is a no 1 website for provide easy codes and build website very easy method. If you are a devloper then we also help you because we also provide, How to solve error and warnings so please use it and save your time and make money with us…
Thank you…
0 notes
mesak · 2 years ago
Text
[JS] Table 轉 Object 練習 part1
[JS] Table 轉 Object 練習 part1
自從工作開始分前後端分離之後,JavaScript 的東西就比較少去鑽研,但近期又開始大量的用到 JS 的東西,有些東西就需要重複的使用,JS 的陣列變化,從以前學會的 jQuery each ,演變到可以直接 querySelectorAll 之後 跑個 forEach 真的很方便,大大減少了對 jQuery 的依賴程度,反而開始探究起 JS 的原生有哪些 function 可以玩 這個時候 MDN 就是個很好用的工具 寫程式不需要一步到位,逐步漸進的達成目的,有機會再去把程式碼精簡調校,能夠理解其原理才會是最好的解法 這次就簡單的寫個當遇到表格,要怎麼轉成 一般的 Plain Object ,這個也是我用 Greasemonkey 要爬 dom 的時候,很常用到的用法,就是把 DOM 轉換成 資料傳遞 首先來一個範例 Continue reading Untitled
View On WordPress
0 notes
ecomsolver · 7 years ago
Text
How to show x-left in configurable product in Magento2
Tumblr media
In a modern world, an e-commerce platform Magento is well known for its flexibility and open-source ecosystem.  It is powerful enough to handle all type of businesses ranging from small cap to large enterprises. To run a successful ecommerce store it requires great efforts to be done by the store owner to maintain products and all. Many products sold online comes in different size, color, length. While displaying these products on the front end, it is important to make the options clear as well as variations in quantity left in stock.
Recently our developer has made an extension on how to show x-left in a configurable product in Magento 2. The script shows the number of variant according to specific length and size. Actually, that script is pretty useful for everyone so we decided to share the script on our blog.
Tumblr media
The particular product is selected. 
Load the stock_threshold_qty and product qty
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
$qtyPro = $StockState->getStockQty($_product->getId(), $_product->getStore()->getWebsiteId());
$conf = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface')->getValue('cataloginventory/options/stock_threshold_qty', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
Tumblr media
Specific size and length of a configurable product is selected
get current product
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');
$mTo = $product->getResource()->getAttribute('mto')->getFrontend()->getValue($product);
//get current product
$productTypeInstance = $product->getTypeInstance();
$configId = $product->getTypeId();
//Main configurable product ID
//echo $product->getName(); //Main Configurable Name
Check if product type is configurable and has option:-
<?php if ($configId == 'configurable') { ?>
<?php
$usedProducts = $productTypeInstance->getUsedProducts($product);
foreach ($usedProducts as $child) {
$sId = $child->getSize(); //Child Product Sku
$skU = $child->getSku(); //Child Product Sku
$sId_Length = $child->getLength(); //Child Product Sku
$qtyProd = $StockState->getStockQty($child->getId(), $child->getStore()->getWebsiteId());
$siZe = $child->getResource()->getAttribute('size')->getFrontend()->getValue($child);
if($siZe)
{
//echo "size h";
//echo "<br>";
}          
$lenGth = $child->getResource()->getAttribute('length')->getFrontend()->getValue($child);
if($lenGth !="No")
{
//echo "length h";
//echo "<br>";
}          
?>
<?php if ($qtyProd < $conf && $qtyProd > 0) { ?>
<div style="margin-top:-21px;" id="remaining_<?php echo $sId; ?>_<?php echo $sId_Length;?>" style="visibility:hidden;" class="availability only" title="Only <?php echo $qtyPro; ?> left">
Only <span style="line-height: 20px;" class="counter-label"><?php echo $qtyProd; ?></span> left in <?php echo $skU; ?>
</div>
<?php //echo "<br>"; ?>
<?php } } } ?>
Place the small js script end of the file –
<script>
require(['jquery'],
function($) {
setTimeout(function(){
var pri_id = 0;
$(".length .swatch-option").on("click", function(){
var se = $('.swatch-attribute.size').attr('option-selected');
if(se>0){
var r = $(this).attr('option-id');
$('#remaining_'+se+'_'+r).css("visibility","visible");
var hidden_text = $('#remaining_id').val();
$('#'+hidden_text).css("visibility","hidden");
$('#remaining_id').val('remaining_'+se+'_'+r);
}
});
$(".size .swatch-option").on("click", function(){
var se = $('.swatch-attribute.length').attr('option-selected');
if(se===undefined){
var r = $(this).attr('option-id');
$('#remaining_'+r+'_').css("visibility","visible");
var hidden_text = $('#remaining_id').val();
$('#'+hidden_text).css("visibility","hidden");
$('#remaining_id').val('remaining_'+r+'_');
}else{
var r = $(this).attr('option-id');
$('#remaining_'+r+'_'+se).css("visibility","visible");
var hidden_text = $('#remaining_id').val();
$('#'+hidden_text).css("visibility","hidden");
$('#remaining_id').val('remaining_'+r+'_'+se);
}
});
}, 2000);
});
</script>
Tumblr media
Specific product of selected size and length has been added to the cart.
Hope you like and find this small solution a useful one. Ecomsolver is a company promoted by a group of highly experienced professionals. Specializes in providing top-notch web solutions through innovation and use of latest technology. Contact us now for more queries related to web.
1 note · View note
priscillagrrr · 5 years ago
Text
0 notes
quizseries · 5 years ago
Text
how to use promises inside for loop in jquery
how to use promises inside for loop in jquery
Tumblr media
Hi I have written and developed this site so that students may learn computer science related technologies easily. I am committed to provide easy and in depth tutorials on various technologies. No one is perfect in this world and nothing is impossible. I give my best for you. I hope it will help you….Thanks
Codetriks is an educational website which is provide  IT Tutorial .
In IT we provide Jquery Tutorial for beginners so learn jquery  and increase your knowledge with us.
Codetriks provide IT tutorials – Codetriks | Jquery AJAX ,Jquery Basic,Jquery Selectors,Curd Operation using Jquery,Insert using jquery,Update using Jquery,Delete using jquery,Jquery grid,Jquery JTemplate,check uncheck checkbox using jquery,jquery onclick events,jquery Insert update delete code,jquery table ,jquery css,jquery foreach function,jquery tutorial,jquery sample demo,jquery examples Our  website provide codes for every technology so please use this website. And also give me feedback how you feel.
Codetriks is a no 1 website for provide easy codes and build website very easy method. If you are a devloper then we also help you because we also provide, How to solve error and warnings so please use it and save your time and make money with us…
Thank you…
0 notes
holytheoristtastemaker · 5 years ago
Link
Tumblr media
A nice list of HTML, CSS and JavaScript How Tos with basic concepts for everyday use. Feel free to comment your own approaches :)
Disabling everything with CSS
CSS
.disabled { filter: grayscale(1); pointer-events: none; }
View on JSFiddle here.
Split an array into chunks without mutability
JS
const array = [1, 2, 3, 4] const size = 3 const new_array = array.reduce((acc, a, i) => { i % size ? acc[parseInt(i / size)].push(a) : acc.push([a]) return acc }, [])
or even shorter:
const new_array = array.reduce((acc, a, i) => i % size ? acc : [...acc, array.slice(i, i + size)], [])
Remember, start using const, if you need to change its value then use let and avoid as much as possible var. View on JSFiddle here.
Saving and loading dates
Save your datetime always in UTC ISO and load it to the user interface using local ISO. Use native widgets to avoid facing date format preferences (middle endian, little endian, etc) HTML
<input type="datetime-local"> <button>Save</button> <button>Load</button>
JS
$button_save.onclick = () => localStorage.setItem('datetime', $input.value && new Date($input.value).toISOString()) $button_load.onclick = () => $input.value = localStorage.getItem('datetime') && toLocalISOString(new Date(localStorage.getItem('datetime'))) .slice(0, -8) function toLocalISOString(d) { const offset = d.getTimezoneOffset() return new Date( d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes() - offset, d.getSeconds(), d.getMilliseconds()).toISOString() }
View on JSFiddle here. I recommend using sessionStorage and localStorage. Do not abuse cookies if they are not strictly necessary. If you need more local storage you can use IndexedDB.
Select HTML table columns by clicking on the headers
JS
document.querySelectorAll('th').forEach($th => $th.onclick = event => { document.querySelectorAll(`td:nth-of-type(${event.currentTarget .cellIndex + 1})`) .forEach($td => $td.classList.toggle('selected')) })
Remember, onclick always overwrites the previous function (in case there was any), use addEventListener() for multiple functions. View on JSFiddle here.
Rename when destructuring
We are going to rename time property while sorting our array of objects. JS
let times = [ {name:'dog', time: '10:23'}, {name: 'laundry', time: '09:34'}, {name: 'work', time: '11:00'}] times.sort(({ time: a }, { time: b }) => a < b ? -1 : a > b ? 1 : 0)
Remember, sort() changes the orginal array. View on JSFiddle here.
Autocomplete dropdown
Have you ever used autocomplete dropdowns from jQuery UI or Bootstrap third party options? A complete heavyweight mess. Luckly, we got a couple of years ago an awaited solution: Native HTML5 Autocomplete dropdown with datalist. A lightweight standard supported in all devices. HTML
<input list="series"> <datalist id="series"> <option value="Adventure Time"> <option value="Rick and Morty"> <option value="Game of Thrones"> <option value="Planet Earth 2"> </datalist>
View on JSFiddle here. Save your tooling time and dependency, use as few libraries and frameworks as possible!
Real easy responsiveness with CSS Grid
CSS Grid is the easiest, cleanest and powerful way to deal with responsiveness, a completely new approach baked in the last years and ready to use. CSS Grid changes how you used to layout your documents, instead of divitis (plenty of divs) and JavaScript to change div positions depending on screens (what Bootstrap does nowadays), you can use pure CSS grid layouts with just the meaningful divs and independently of document source order. You don’t need to touch HTML or JavaScript, you don’t need Bootstrap or even complex CSS rules, what you see in your CSS is what you get on your screen. HTML
<div class="grid"> <div class="name">Name</div> <div class="score">Score</div> <div class="skills">Skills</div> <div class="chart">Chart</div> </div>
CSS
.grid { display: grid; grid-template-areas: "name" "score" "skills" "chart"; } @media only screen and (min-width: 500px) { .grid { grid-template-areas: "name skills" "score skills" "chart chart"; } } .name { grid-area: name; } .score { grid-area: score; } .skills { grid-area: skills; } .chart { grid-area: chart; }
View on JSFiddle here. I would recommend you to do these examples. Fall in love with Grid Templates like I did ❤
Move parts of the user interface without loss of interaction
HTML
<ul> <li> <button id="up">Up</button> <button id="down">Down</button> </li> <li>Nothing</li> <li>Nothing</li> </ul>
JS
document.querySelector('#up').onclick = e => { const $li = e.target.parentElement if ($li.previousElementSibling) $li.parentElement.insertBefore($li, $li.previousElementSibling) } document.querySelector('#down').onclick = e => { const $li = e.target.parentElement if ($li.nextElementSibling) $li.parentElement.insertBefore($li.nextElementSibling, $li) }
Remember, target is what triggers the event and currentTarget is what you assigned your listener to. View on JSFiddle here.
HTML input time with 24 hours format
Rely on native HTML widgets without depending on third party libraries. However, sometimes there are some limitations, if you have ever dealt with an HTML input time you know what it is about, try to set up maximum or minimum hours/minutes and/or change from 12 hours format to 24 hours and viceversa. By now, a good solution to avoid headaches is to use 2 inputs of the type number and a pinch of JS. HTML
<div> <input type="number" min="0" max="23" placeholder="23">: <input type="number" min="0" max="59" placeholder="00"> </div>
CSS
div { background-color: white; display: inline-flex; border: 1px solid #ccc; color: #555; } input { border: none; color: #555; text-align: center; width: 60px; }
JS
document.querySelectorAll('input[type=number]') .forEach(e => e.oninput = () => { if (e.value.length >= 2) e.value = e.value.slice(0, 2) if (e.value.length == 1) e.value = '0' + e.value if (!e.value) e.value = '00' })
Remember, == double comparation for equality and === triple one for equality and type. If you want to check whether a variable is undefined or not, simple use triple compartion a === undefined and the same for null. If you want to check whether it exists or not use typeof a != 'undefined'. View on JSFiddle here.
Loop n times without mutable variables
JS
[...Array(10).keys()] .reduce((sum, e) => sum + `<li>${e}</li>`, '')
also like this:
[...Array(10)] .reduce((sum, _, i) => sum + `<li>${i}</li>`, '')
View on JSFiddle here.
Horizontal and vertical center
Forget about any complicated way, just use Flexbox and set up horizontal center and vertical center in the container. CSS
body { position: absolute; top: 0; right: 0; bottom: 0; left: 0; display: flex; justify-content: center; align-items: center; } div { background-color: #555; width: 100px; height: 100px; }
View on JSFiddle here.
Asynchronous fetch
Using fetch() with asyncronous functions. JS
async function async_fetch(url) { let response = await fetch(url) return await response.json() } async_fetch(‘https://httpbin.org/ip') .then(data => console.log(data)) .catch(error => console.log('Fetch error: ' + error))
View on JSFiddle here. Note, as you have noticed I don’t write the ; semicolon, that’s perfectly fine, in JavaScript the ; is not mandatory, it doesn’t matter if you write it or not, the JS engine is going to check it and insert it if needed, just be careful with new lines that start with ( parentesis and avoid return with the value in a diferent line.
Footer with right and left buttons
HTML
<footer> <div> <button>Button A</button> <button>Button B</Button> </div> <div> <button>Button C</button> <button>Button D</button> </div> </footer>
CSS
footer { display: flex; justify-content: space-between; position: fixed; bottom: 0; left: 0; right: 0; }
View on JSFiddle here.
Scroll into view
I have created n boxes (divs) with random colors to select one of them randomly and make it visible on the viewport. Every time you rerun the code you will see in your screen the selected box regardless of its position. JS
document.querySelector(`div:nth-child(${random})`).scrollIntoView()
View on JSFiddle here.
Flattening arrays of objects
JS
array = alphas.map(a => a.gammas.map(g => g.betas) ).join()
If you want to see other different approaches using forEach with concat and with push check this link (I did also some time consuming test using jsPerf). View on JSFiddle here. Remember, in case you want to flat arrays of arrays you can do it easily with flat().
[1, 2, [3, 4, [5, 6]]].flat(Infinity)
Nesting arrays of objects
Returns an array of n elements filled with content: JS
let get_array = (n, content) => Array(n).fill(content)
Returns an object with a name property that has a content value:
let get_object = (name, content) => Object.defineProperty({}, name, {value: content})
3 levels of arrays with objects (nested)
a = get_array(3, get_object('b', get_array(6, get_object('c', get_array(3, {}) )) ))
View on JSFiddle here.
Array without duplicate values
JS
const array = [1, 2, 3, 3, 3, 2, 1]
The Set strategy:
[...new Set(array)]
The filter strategy (easier to figure out but slower):
array.filter((elem, index) => index == array.indexOf(elem))
View on JSFiddle here. Remember, Array.from(iterableObj) = [...iterableObj]
HTML input with units
HTML
<span><input type="number" min="0" value="50">€</span>
CSS
span { background: white; border: 1px solid #e8e8e8; } input { background: inherit; outline: none; border: none; padding: 0 5px; }
View on JSFiddle here.
Responsive background loop video
HTML
<video autoplay loop poster="https://website/video.jpg"> <source src="http://website/video.webm"> </video>
CSS
video.landscape { width: 100vw; height: auto; } video { width: auto; height: 100vh; }
Remember, you can add as many sources as you want to support different video formats. View on JSFiddle here.
How to print specific HTML content
If you want to print a specific HTML content, for example everything inside a div tag or a tag element with a particular identifier, you can use window.print() in a new window with just the content you want to. It’s easy but tricky, we would like an accessible print method for any HTML element but there aren’t. Don’t forget to add/link some CSS in your new window otherwise you will get the default style from your browser. JS, HTML, CSS
function print(content) { let win = window.open() win.document.write(` <html><head> <title>Report</title> <style> div { display: inline-flex; width: 200px; height: 200px; justify-content: center; align-items: center; background-color: #e9a9c7; color: #39464e; } </style> </head><body>` ) win.document.write(content) win.document.write('</body></html>') win.print() win.close() }
View on JSFiddle here. Note, the write method is synchronous, however sometimes window tries to print before write has finished, it happens only in some browsers ¬¬, therefore trying to avoid this we have added a setTimeout(). Yeah, no quite elegant but among all the different ways, it is the shortest that works across all updated browsers so far.
View, hide, type and generate password
Love to make things as simple as possible xD A hint just inside the input, then a button to show the password and finally another button to generate random passwords. HTML
<input id="password" type="password" placeholder="type password..."> <button id="view-password"></button> <button id="generate-password">↻</button>
View or hide password: JS
$view_password.addEventListener('click', e => { e.currentTarget.classList.toggle('view') if (e.currentTarget.className.includes('view')) $password.setAttribute('type', 'text') else $password.setAttribute('type', 'password') })
Set a random password and make sure it’s shown:
$generate_password.addEventListener('click', () => { $view_password.classList.add('view') $password.setAttribute('type', 'text') $password.value = Math.random().toString(36).slice(-8) })
View on JSFiddle here. Note, I personally name selector’s const starting with a $.
Infinite previous and next selection
Select each element in a selection loop. If you go forward as soon as you finish the list of elements you will start selecting from the beginning and the same if you go in opposite direction. HTML
<button id="previous">Previous</button> <button id="next">Next</button> <ul> <li></li> <li class="selected"></li> <li></li> <li></li> <li></li> </ul>
JS
document.querySelector('#next').addEventListener('click', () => { const $selected = document.querySelector('.selected') const $next_element = $selected.nextElementSibling if (!$next_element) $next_element = $selected.parentElement.firstElementChild $selected.classList.remove('selected') $next_element.classList.add('selected') })
Remember, use nextElementSibling and previousElementSibling (DOM elements) instead of nextSibling and previousSibling (DOM objects). A DOM Object can be anything: comments, insolated text, line breaks, etc. In our example nextSibling would have worked if we had set all our HTML elements together without anything between then:
<ul><li></li><li></li></ul>
View on JSFiddle here.
Responsive square
I have seen many weird ways to create responsive squares, that’s why I would like to share an easy one. Go to the JSFiddle link below and play resizing the result window. CSS
div { width: 60vw; height: 60vw; margin: 20vh auto; background-color: #774C60; }
View on JSFiddle here.
Circle area defined by mouse click
We are going to define the area of a circle depending on where we click within a box area. We can handle this using JavaScript events, a little bit of basic maths and CSS. Width and height are igual, it doesn’t matter which we will set for our maths: JS
const width = e.currentTarget.clientWidth
Absolute position of the mouse cursor from the circle center:
const x = Math.abs(e.clientX — offset.left — width / 2) const y = Math.abs(e.clientY — offset.top — width / 2)
The maximum will tell us the percent of the circle area:
percent = Math.round(2 * Math.max(x, y) * 100 / width) $circle.style.width = percent + '%' $circle.style.height = percent + '%'
Text Overwriting
Well, maybe you are thinking that you can just turn on your Insert key from your keyboard but what If you don’t have it or if you want to always have an overwriting mode (independently) while typing in some specific inputs and textareas. You can do it easily. JS
$input.addEventListener('keypress', function(e) { const cursor_pos = e.currentTarget.selectionStart if (!e.charCode) return $input.value = $input.value.slice(0, cursor_pos) + $input.value.slice(cursor_pos + 1) e.currentTarget.selectionStart = e.currentTarget.selectionEnd = cursor_pos })
View on JSFiddle here.
Counter with a reset using closures
Set up a basic counter with a closure and some external accessible options. JS
const add = (function() { let offset = 0 return function(option) { switch (option) { case 0: offset = 0; break; case 1: offset++; break; case 2: offset — ; break; default: throw ‘Not a valid option’; } console.log(offset) } })()
Remembler, a closure just let you keep recorded and protected your variables. View on JSFiddle here.
Infinite scroll
Have you ever seen those automatic "Load More" while you scroll down? Did you see them on Tumblr for images, Gmail for messages or Facebook? Cool, isn’t it? The infinite scroll is an alternative for pagination and it’s everywhere. It optimizes the user experience loading data as the user required it (indirectly). You get faster loading process for pages, web, apps and it just loads what you need instead of the whole bunch. You don’t need to add extra interactions, buttons or widgets because it comes with the normal reading behaviour that you are used to: scroll down with the mouse or with the finger in a touchable screen. JS
const $ol = document.querySelector('ol') function load_more() { let html = '' for (var i = 0; i < 5; i++) html += '<li></li>' $ol.innerHTML += html } $ol.addEventListener('scroll', function() { if ($ol.scrollHeight — $ol.scrollTop == $ol.clientHeight) load_more() })
View on JSFiddle here. Just notice in the example above that we could make it more efficient creating nodes and using appendChild().
Material icons
HTML
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <i class="material-icons">face</i>
View on JSFiddle here.
Basic CSS transition using box-shadow
Our CSS will change if the mouse is over the element with an ease-in-out transition effect (slow start and end). We are filling up the element with an inner shadow (inset) CSS
i { transition: all 0.5s ease-in-out; box-shadow: 0 0 0 75px #E94F37 inset; } i:hover { box-shadow: 0 0 0 4px #E94F37 inset; color:#E94F37; }
View on JSFiddle here.
Export HTML table to CSV file
Imagine you have an HTML table and you want to download it as a CSV table. HTML
<table> <tr><th>Name</th><th>Age</th><th>Country</th></tr> <tr><td>Geronimo</td><td>26</td><td>France</td></tr> <tr><td>Natalia</td><td>19</td><td>Spain</td></tr> <tr><td>Silvia</td><td>32</td><td>Russia</td></tr> </table>
First of all, you need to transform from HTML to CSV: JS
let csv = [] let rows = document.querySelectorAll('table tr') for (var i = 0; i < rows.length; i++) { let row = [], cols = rows[i].querySelectorAll('td, th') for (var j = 0; j < cols.length; j++) row.push(cols[j].innerText) csv.push(row.join(',')) } download_csv(csv.join('\n'), filename)
After that, you can download it using Blob and a link:
let csvFile = new Blob([csv], {type: 'text/csv'}) let downloadLink = document.createElement('a') downloadLink.download = filename downloadLink.href = window.URL.createObjectURL(csvFile) downloadLink.style.display = 'none' document.body.appendChild(downloadLink) downloadLink.click()
View on JSFiddle here.
Keyboard events
Use event.code to get a human readable way of knowing which keys are pressed. Use event.key if you want to distinguish between capital letter or not, and avoid browser shortcuts, i.e: Ctrl + P (print) JS
document.onkeydown = event => { switch (event.code) { case ‘ArrowDown’: $div.style.top = `${parseInt($div.style.top || 0) + step}px` break case ‘KeyR’: if (event.altKey) $div.style.top = 0 break } }
View on JSFiddle here.
Short selectors like jQuery
Using JavaScript is some kind of annoying when you have to select DOM elements, in those cases we could miss jQuery because vanilla JavaScript is simply too long. JS
// Select one element (first one) document.querySelector('#peter') document.querySelector('.staff') document.querySelector('.staff').querySelector('.age') // Select all elements document.querySelectorAll('.staff')
We don’t like to repeat things when we are coding, if you define the next code at the beginning of your JavaScript you will be avaliable to do it similar even better than jQuery.
function $(selector) { return document.querySelector(selector) } function $$(selector) { return document.querySelectorAll(selector) } Element.prototype.$ = function(selector) { return this.querySelector(selector) } Element.prototype.$$ = function(selector) { return this.querySelectorAll(selector) }
Now you can write our example shorter:
// Select one element $('#peter') $('.staff') $('.staff').$('.age') // Select all elements $$('.staff')
It’s easy to keep in mind because $ behaves like jQuery with CSS selectors and $$ does the same but it allows you to select multiple elements. The first one return the element and the second one a list of elements. Just one more thing, you cannot use jQuery with this code because jQuery use $ too, if you need it you have to change the $ in our code for another thing, ie: qS. Remember, in JavaScript we have something better than classes: prototype. It doesn’t matter if you use class, under the hood is using prototype.
Which is the different between property and attribute?
A property is in the DOM; an attribute is in the HTML that is parsed into the DOM. HTML
<body onload="foo()">
JS
document.body.onload = foo
Avoid switch statement when you don’t need logic
Arrays are faster, in the next example if you want to now which is the nineth month you can just code months[9]. JS
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
0 notes
t-baba · 5 years ago
Photo
Tumblr media
How to Make a Simple JavaScript Quiz
Tumblr media
"How do I make a JavaScript quiz?" is one of the most common questions asked by people learning web development, and for good reason. Quizzes are fun! They’re a great way of learning about new subjects, and they allow you to engage your audience with something fun and playful.
Tumblr media
Coding your own JavaScript quiz is also a fantastic learning exercise. It teaches you how to deal with events, manipulate the DOM, handle user input, give feedback to the user and keep track of their score (for example, using client-side storage). And when you have a basic quiz up and running, there are a whole bunch of possibilities to add more advanced functionality, such as pagination. I go into this at the end of the article.
In this tutorial, I’ll walk you though creating a multi-step JavaScript quiz which you’ll be able to adapt to your needs and add to your own site. If you'd like to see what we'll be ending up with, you can skip ahead and see the working quiz.
Things to Be Aware of Before Starting
A few things to know before starting:
This is a front-end tutorial, meaning that anyone who knows how to look through the source code of a page can find the answers. For serious quizzes, the data needs to be handled through the back end, which is beyond the scope of this tutorial.
The code in this article uses modern JavaScript syntax (ES6+), meaning it will not be compatible with any versions of Internet Explorer. However, it will work just fine on modern browsers, including Microsoft Edge.
If you need to support older browsers, I've written a JavaScript quiz tutorial that's compatible back to IE8. Or, if you'd like a refresher on ES6, check out this course by Darin Haener over on SitePoint Premium.
You'll need some familiarity with HTML, CSS, and JavaScript, but each line of code will be explained individually.
The Basic Structure of Your JavaScript Quiz
Ideally, we want the quiz's questions and answers to be in our JavaScript code and have our script automatically generate the quiz. That way, we won't need to write a lot of repetitive markup, and we can add and remove questions easily.
To set up the structure of our JavaScript quiz, we'll need to start with the following HTML:
A <div> to hold the quiz
A <button> to submit the quiz
A <div> to display the results
Here's how that would look:
<div id="quiz"></div> <button id="submit">Submit Quiz</button> <div id="results"></div>
We can then select these HTML elements and store references to them in variables like so:
const quizContainer = document.getElementById('quiz'); const resultsContainer = document.getElementById('results'); const submitButton = document.getElementById('submit');
Next we'll need a way to build a quiz, show results, and put it all together. We can start by laying out our functions, and we'll fill them in as we go:
function buildQuiz(){} function showResults(){} // display quiz right away buildQuiz(); // on submit, show results submitButton.addEventListener('click', showResults);
Here, we have functions to build the quiz and show the results. We'll run our buildQuiz function immediately, and we'll have our showResults function run when the user clicks the submit button.
Displaying the Quiz Questions
The next thing our quiz needs is some questions to display. We'll use object literals to represent the individual questions and an array to hold all of the questions that make up our quiz. Using an array will make the questions easy to iterate over:
const myQuestions = [ { question: "Who invented JavaScript?", answers: { a: "Douglas Crockford", b: "Sheryl Sandberg", c: "Brendan Eich" }, correctAnswer: "c" }, { question: "Which one of these is a JavaScript package manager?", answers: { a: "Node.js", b: "TypeScript", c: "npm" }, correctAnswer: "c" }, { question: "Which tool can you use to ensure code quality?", answers: { a: "Angular", b: "jQuery", c: "RequireJS", d: "ESLint" }, correctAnswer: "d" } ];
Feel free to put in as many questions or answers as you want.
Note: as this is an array, the questions will appear in the order they’re listed. If you want to sort the questions in any way before presenting them to the user, check out our quick tip on sorting an array of objects in JavaScript.
Now that we have our list of questions, we can show them on the page. We'll go through the following JavaScript line by line to see how it works:
function buildQuiz(){ // variable to store the HTML output const output = []; // for each question... myQuestions.forEach( (currentQuestion, questionNumber) => { // variable to store the list of possible answers const answers = []; // and for each available answer... for(letter in currentQuestion.answers){ // ...add an HTML radio button answers.push( `<label> <input type="radio" name="question${questionNumber}" value="${letter}"> ${letter} : ${currentQuestion.answers[letter]} </label>` ); } // add this question and its answers to the output output.push( `<div class="question"> ${currentQuestion.question} </div> <div class="answers"> ${answers.join('')} </div>` ); } ); // finally combine our output list into one string of HTML and put it on the page quizContainer.innerHTML = output.join(''); }
First, we create an output variable to contain all the HTML output including questions and answer choices.
Next, we can start building the HTML for each question. We'll need to loop through each question like so:
myQuestions.forEach( (currentQuestion, questionNumber) => { // the code we want to run for each question goes here });
For brevity, we're using an arrow function to perform our operations on each question. Because this is in a forEach loop, we get the current value, the index (the position number of the current item in the array), and the array itself as parameters. We only need the current value and the index, which for our purposes, we'll name currentQuestion and questionNumber respectively.
Now let's look a the code inside our loop:
// we'll want to store the list of answer choices const answers = []; // and for each available answer... for(letter in currentQuestion.answers){ // ...add an html radio button answers.push( `<label> <input type="radio" name="question${questionNumber}" value="${letter}"> ${letter} : ${currentQuestion.answers[letter]} </label>` ); } // add this question and its answers to the output output.push( `<div class="question"> ${currentQuestion.question} </div> <div class="answers"> ${answers.join('')} </div>` );
For each question, we'll want to generate the correct HTML, and so our first step is to create an array to hold the list of possible answers.
Next, we'll use a loop to fill in the possible answers for the current question. For each choice, we're creating an HTML radio button, which we enclose in a <label> element. This is so that users will be able to click anywhere on the answer text to select that answer. If the label was omitted, then users would have to click on the radio button itself, which is not very accessible.
Notice we're using template literals, which are strings but more powerful. We'll make use of the following features:
multi-line capabilities
no more having to escape quotes within quotes because template literals use backticks instead
string interpolation, so you can embed JavaScript expressions right into your strings like this: ${code_goes_here}.
Once we have our list of answer buttons, we can push the question HTML and the answer HTML onto our overall list of outputs.
Notice that we're using a template literal and some embedded expressions to first create the question div and then create the answer div. The join expression takes our list of answers and puts them together in one string that we can output into our answers div.
Now that we've generated the HTML for each question, we can join it all together and show it on the page:
quizContainer.innerHTML = output.join('');
Now our buildQuiz function is complete.
You should be able to run the quiz at this point and see the questions displayed. Please note, however, that the structure of your code is important. Due to something called the temporal dead zone, you can’t reference your questions array before it has been defined.
To recap, this is the correct structure:
// Functions function buildQuiz(){ ... } function showResults(){ ... } // Variables const quizContainer = document.getElementById('quiz'); const resultsContainer = document.getElementById('results'); const submitButton = document.getElementById('submit'); const myQuestions = [ ... ]; // Kick things off buildQuiz(); // Event listeners submitButton.addEventListener('click', showResults);
Displaying the Quiz Results
At this point, we want to build out our showResults function to loop over the answers, check them, and show the results.
Here's the function, which we'll go through in detail next:
function showResults(){ // gather answer containers from our quiz const answerContainers = quizContainer.querySelectorAll('.answers'); // keep track of user's answers let numCorrect = 0; // for each question... myQuestions.forEach( (currentQuestion, questionNumber) => { // find selected answer const answerContainer = answerContainers[questionNumber]; const selector = `input[name=question${questionNumber}]:checked`; const userAnswer = (answerContainer.querySelector(selector) || {}).value; // if answer is correct if(userAnswer === currentQuestion.correctAnswer){ // add to the number of correct answers numCorrect++; // color the answers green answerContainers[questionNumber].style.color = 'lightgreen'; } // if answer is wrong or blank else{ // color the answers red answerContainers[questionNumber].style.color = 'red'; } }); // show number of correct answers out of total resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.length}`; }
First, we select all the answer containers in our quiz's HTML. Then we'll create variables to keep track of the user's current answer and the total number of correct answers.
// gather answer containers from our quiz const answerContainers = quizContainer.querySelectorAll('.answers'); // keep track of user's answers let numCorrect = 0;
Now we can loop through each question and check the answers.
// for each question... myQuestions.forEach( (currentQuestion, questionNumber) => { // find selected answer const answerContainer = answerContainers[questionNumber]; const selector = `input[name=question${questionNumber}]:checked`; const userAnswer = (answerContainer.querySelector(selector) || {}).value; // if answer is correct if(userAnswer === currentQuestion.correctAnswer){ // add to the number of correct answers numCorrect++; // color the answers green answerContainers[questionNumber].style.color = 'lightgreen'; } // if answer is wrong or blank else{ // color the answers red answerContainers[questionNumber].style.color = 'red'; } });
The general gist of this code is:
find the selected answer in the HTML
handle what happens if the answer is correct
handle what happens if the answer is wrong.
Let's look more closely at how we're finding the selected answer in our HTML:
// find selected answer const answerContainer = answerContainers[questionNumber]; const selector = `input[name=question${questionNumber}]:checked`; const userAnswer = (answerContainer.querySelector(selector) || {}).value;
First, we're making sure we're looking inside the answer container for the current question.
In the next line, we're defining a CSS selector that will let us find which radio button is checked.
Then we're using JavaScript's querySelector to search for our CSS selector in the previously defined answerContainer. In essence, this means that we'll find which answer's radio button is checked.
Finally, we can get the value of that answer by using .value.
Dealing with Incomplete User Input
But what if the user has left an answer blank? In this case, using .value would cause an error because you can't get the value of something that's not there. To solve this, we've added ||, which means "or", and {}, which is an empty object. Now the overall statement says:
Get a reference to our selected answer element OR, if that doesn't exist, use an empty object.
Get the value of whatever was in the first statement.
As a result, the value will either be the user's answer or undefined, which means a user can skip a question without crashing our quiz.
Evaluating the Answers and Displaying the Result
The next statements in our answer-checking loop will let us handle correct and incorrect answers.
// if answer is correct if(userAnswer === currentQuestion.correctAnswer){ // add to the number of correct answers numCorrect++; // color the answers green answerContainers[questionNumber].style.color = 'lightgreen'; } // if answer is wrong or blank else{ // color the answers red answerContainers[questionNumber].style.color = 'red'; }
If the user's answer matches the correct choice, increase the number of correct answers by one and (optionally) color the set of choices green. If the answer is wrong or blank, color the answer choices red (again, optional).
Once the answer-checking loop is finished, we can show how many questions the user got right:
// show number of correct answers out of total resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.length}`;
And now we have a working JavaScript quiz!
If you'd like, you can wrap the whole quiz in an IIFE (immediately invoked function expression), which is a function that runs as soon as you define it. This will keep your variables out of global scope and ensure that your quiz doesn't interfere with any other scripts running on the page.
(function(){ // put the rest of your code here })();
The post How to Make a Simple JavaScript Quiz appeared first on SitePoint.
by Yaphi Berhanu via SitePoint https://ift.tt/3bxa8uf
0 notes
eazy-group · 2 years ago
Text
Strongwoman Kira Wrixson (U64 KG) Locks Out 6-Times Body Weight with a Monstrous 385.5-Kilogram (850-Pound) 18-Inch Deadlift
New Post has been published on https://eazyfitness.net/strongwoman-kira-wrixson-u64-kg-locks-out-6-times-body-weight-with-a-monstrous-385-5-kilogram-850-pound-18-inch-deadlift/
Strongwoman Kira Wrixson (U64 KG) Locks Out 6-Times Body Weight with a Monstrous 385.5-Kilogram (850-Pound) 18-Inch Deadlift
Tumblr media
[] Strongwoman Kira Wrixson (U64 KG) Locks Out 6-Times Body Weight with a Monstrous 385.5-Kilogram (850-Pound) 18-Inch Deadlift – Breaking Muscle
0);var b=document.getElementsByTagName(“body”)[0];var config=childList:!0,subtree:!0;observer.observe(b,config),!1)]]>=0?”perfmatters-“+r:re[t]function r(e,t)let r=e[t];Object.defineProperty(e,t,function(),set:function(r)e[“perfmatters”+t]=r)t(document,”DOMContentLoaded”),t(window,”DOMContentLoaded”),t(window,”load”),t(window,”pageshow”),t(document,”readystatechange”),r(document,”onreadystatechange”),r(window,”onload”),r(window,”onpageshow”)}function pmDelayJQueryReady()let e=window.jQuery;Object.defineProperty(window,”jQuery”,get:()=>e,set(t)if(t&&t.fn&&!jQueriesArray.includes(t))t.fn.ready=t.fn.init.prototype.ready=function(e)pmDOMLoaded?e.bind(document)(t):document.addEventListener(“perfmatters-DOMContentLoaded”,function()e.bind(document)(t));let r=t.fn.on;t.fn.on=t.fn.init.prototype.on=function()if(this[0]===window)return r.apply(this,arguments),this,jQueriesArray.push(t)e=t)function pmProcessDocumentWrite()let e=new Map;document.write=document.writeln=function(t)var r=document.currentScript,n=document.createRange();let a=e.get(r);void 0===a&&(a=r.nextSibling,e.set(r,a));var i=document.createDocumentFragment();n.setStart(i,0),i.appendChild(n.createContextualFragment(t)),r.parentElement.insertBefore(i,a)function pmSortDelayedScripts()document.querySelectorAll(“script[type=pmdelayedscript]”).forEach(function(e)e.hasAttribute(“src”)?e.hasAttribute(“defer”)&&!1!==e.defer?pmDelayedScripts.defer.push(e):e.hasAttribute(“async”)&&!1!==e.async?pmDelayedScripts.async.push(e):pmDelayedScripts.normal.push(e):pmDelayedScripts.normal.push(e))function pmPreloadDelayedScripts()var e=document.createDocumentFragment();[…pmDelayedScripts.normal,…pmDelayedScripts.defer,…pmDelayedScripts.async].forEach(function(t)var r=t.getAttribute(“src”);if(r)var n=document.createElement(“link”);n.href=r,n.rel=”preload”,n.as=”script”,e.appendChild(n)),document.head.appendChild(e)async function pmLoadDelayedScripts(e)var t=e.shift();return t?(await pmReplaceScript(t),pmLoadDelayedScripts(e)):Promise.resolve()async function pmReplaceScript(e)return await pmNextFrame(),new Promise(function(t)let r=document.createElement(“script”);[…e.attributes].forEach(function(e)let t=e.nodeName;”type”!==t&&(“data-type”===t&&(t=”type”),r.setAttribute(t,e.nodeValue))),e.hasAttribute(“src”)?(r.addEventListener(“load”,t),r.addEventListener(“error”,t)):(r.text=e.text,t()),e.parentNode.replaceChild(r,e))async function pmTriggerEventListeners()pmDOMLoaded=!0,await pmNextFrame(),document.dispatchEvent(new Event(“perfmatters-DOMContentLoaded”)),await pmNextFrame(),window.dispatchEvent(new Event(“perfmatters-DOMContentLoaded”)),await pmNextFrame(),document.dispatchEvent(new Event(“perfmatters-readystatechange”)),await pmNextFrame(),document.perfmattersonreadystatechange&&document.perfmattersonreadystatechange(),await pmNextFrame(),window.dispatchEvent(new Event(“perfmatters-load”)),await pmNextFrame(),window.perfmattersonload&&window.perfmattersonload(),await pmNextFrame(),jQueriesArray.forEach(function(e)e(window).trigger(“perfmatters-jquery-load”));let e=new Event(“perfmatters-pageshow”);e.persisted=window.pmPersisted,window.dispatchEvent(e),await pmNextFrame(),window.perfmattersonpageshow&&window.perfmattersonpageshow(persisted:window.pmPersisted)async function pmNextFrame()return new Promise(function(e)requestAnimationFrame(e))function pmClickHandler(e)e.target.removeEventListener(“click”,pmClickHandler),pmRenameDOMAttribute(e.target,”pm-onclick”,”onclick”),pmInterceptedClicks.push(e),e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()function pmReplayClicks()window.removeEventListener(“touchstart”,pmTouchStartHandler,passive:!0),window.removeEventListener(“mousedown”,pmTouchStartHandler),pmInterceptedClicks.forEach(e=>e.target.outerHTML===pmClickTarget&&e.target.dispatchEvent(new MouseEvent(“click”,view:e.view,bubbles:!0,cancelable:!0)))function pmTouchStartHandler(e)“HTML”!==e.target.tagName&&(pmClickTargetfunction pmTouchMoveHandler(e)window.removeEventListener(“touchend”,pmTouchEndHandler),window.removeEventListener(“mouseup”,pmTouchEndHandler),window.removeEventListener(“touchmove”,pmTouchMoveHandler,passive:!0),window.removeEventListener(“mousemove”,pmTouchMoveHandler),e.target.removeEventListener(“click”,pmClickHandler),pmRenameDOMAttribute(e.target,”pm-onclick”,”onclick”)function pmTouchEndHandler(e)window.removeEventListener(“touchend”,pmTouchEndHandler),window.removeEventListener(“mouseup”,pmTouchEndHandler),window.removeEventListener(“touchmove”,pmTouchMoveHandler,passive:!0),window.removeEventListener(“mousemove”,pmTouchMoveHandler)function pmRenameDOMAttribute(e,t,r)e.hasAttribute&&e.hasAttribute(t)&&(event.target.setAttribute(r,event.target.getAttribute(t)),event.target.removeAttribute(t))window.addEventListener(“pageshow”,e=>window.pmPersisted=e.persisted),pmUserInteractions.forEach(function(e)window.addEventListener(e,pmTriggerDOMListener,passive:!0)),pmDelayClick&&(window.addEventListener(“touchstart”,pmTouchStartHandler,passive:!0),window.addEventListener(“mousedown”,pmTouchStartHandler)),document.addEventListener(“visibilitychange”,pmTriggerDOMListener);]]> Source
0 notes
codetriks · 5 years ago
Text
how to pass array in Post web api using ajax Jquery
how to pass array in Post web api using ajax Jquery
Tumblr media
Hi I have written and developed this site so that students may learn computer science related technologies easily. I am committed to provide easy and in depth tutorials on various technologies. No one is perfect in this world and nothing is impossible. I give my best for you. I hope it will help you….Thanks
Codetriks is an educational website which is provide  IT Tutorial .
In IT we provide Jquery,Mvc,c#.net,Asp.net,SQL,Zendesk,Dapper,Vue Js Tutorial for beginners so learn and increase your knowledge with us.
Codetriks provide IT tutorials – Codetriks | Jquery AJAX ,Jquery Basic,Jquery Selectors,Curd Operation using Jquery,Insert using jquery,Update using Jquery,Delete using jquery,Jquery grid,Jquery JTemplate,check uncheck checkbox using jquery,jquery onclick events,jquery Insert update delete code,jquery table ,jquery css,jquery foreach function,jquery tutorial,jquery sample demo,jquery examples Our  website provide codes for every technology so please use this website. And also give me feedback how you feel.
Codetriks is a no 1 website for provide easy codes and build website very easy method. If you are a devloper then we also help you because we also provide, How to solve error and warnings so please use it and save your time and make money with us…
Thank you…
0 notes
ahbusinesstechnology · 6 years ago
Text
The best code snippets Wordpress for your website
Tumblr media
Before publishing this post, we already know how to add PHP functions in Wordpress via using tools. However, I want to share with you some useful functions that either you or any web developers need to know for customising website.  Furthermore, these functions can make your website more responsive, more security and more cool. In addition, these function can save your money (without using paid plugin), save much time for coding and test. Therefore, I create a list of 20 cool customised functions that can support you to select the most essential FUNCTIONS that you really need for your website. These functions are compatible with most popular themes and most of Wordpress versions. Besides, I will update more functions in this post for easy reviewing. In addition, the table of content on the right sidebar will support you to navigate easily. Before implementing the process, you need to concentrate on some important steps. READ THIS CAREFULLY BEFORE YOU GO  Backup you website Separate each function below for testing before officially activating. You can use plugin snippets or other plugins or separated it in function.php. During testing, if it conflicts, incompatible or make errors on your theme, you can remove it, safely. You just copy and paste PHP code to snippet plugin and activate it. It begins with " " I already tested all codes below, It works like a charm. So if you have question or error code that need for support. You can leave your comment below. I will give you feedback asap. It could be including "How to use" and "CSS" parts. " " shows you how to display the function's result in html markup or insert it directly into posts. Therefore, you do not need to copy it into function.php or code snippet. Besides, " " supports you to decorate Html code block. Code snippets compatibility: Wordpress version > 4.6 PHP ~ 7.xx  
Snippets index
  Enqueue Google Fonts This function will add more style for your google font function google_fonts() { wp_register_style('OpenSans', 'https://fonts.googleapis.com/css?family=Open+Sans:400,400i,600i,700,700i,800'); wp_enqueue_style( 'OpenSans'); } add_action( 'wp_print_styles', 'google_fonts' ); ?> Make jQuery load from Google Library The function support to load google library in front pages. function replace_jquery() { if (!is_admin()) { wp_deregister_script('jquery'); wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js', false, '1.11.0'); wp_enqueue_script('jquery'); } } add_action('init', 'replace_jquery'); ?> Customize excerpt length and read more characters Sometimes you need a special length of the excerpt for a specific template. The following function can be used to set this length as desired. The good thing is that the excerpt length is not set globally, but each template can have its own length. function ahlbtech_excerpt_length( $length ) { return 50; } add_filter( 'excerpt_length', 'ahlbtech_excerpt_length', 999 ); //Custom Read More Excerpt function ahlbtech_excerpt_more( $more ) { return '...'; } add_filter('excerpt_more', 'ahlbtech_excerpt_more'); ?> // Deleting the original tag: // Exchange with this tag, and enter any length (in brackets): Enable Pagination Links The function enable pagination links in front page. You want the old »Older posts | Newer posts «Replace links with a cool number list? No problem, since the WordPress version 4.1 you need for the well-known plugin WP-PageNavi no longer. Now that's easy with on-board resources. if ( ! function_exists( 'ahlbtech_pagination' ) ) : function ahlbtech_pagination() { global $wp_query; $big = 999999999; // need an unlikely integer echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $wp_query->max_num_pages, 'prev_text' => 'Newer Posts', 'next_text' => 'Older Posts' ) ); } endif; ?> /*---For the list to get a design, it still needs some CSS. Here are the styles that I use now and then. You still need to adjust it to your blog colors--*/ nav.pagination{position:relative;display:block;margin-top:20px} .page-numbers{margin:0;padding:0} .page-numbers li{list-style:none;margin:0 6px 0 0;padding:0;display:inline-block} .page-numbers li span.current{padding:10px 15px;background:#9FC65D;border:1px solid #9FC65D;display:block;line-height:1;color:#fff} .page-numbers li a{padding:10px 15px;background:#eee;color:#555;text-decoration:none;border:1px solid #eee;display:block;line-height:1} .page-numbers li a:hover{background:#9FC65D;border-color:#9FC65D;color:#fff} .screen-reader-text { clip: rect(1px,1px,1px,1px); position: absolute!important; height: 1px; width: 1px; overflow: hidden; } Replace WP login logo with custom If you feel so boring with old logo login style, you can replace it with your new logo as you want. Furthermore, if you are really proud of your WordPress website and have invested a lot of work in the design? Then go a step further and adjust the logo on the login page. It looks really good together with a background color of its own. function ahlbtech_login_logo() { ?> #login h1 a, .login h1 a { background-image: url(/images/LOGO.png); background-size: 260px 110px; width: 260px; height: 110px; } add_action( 'login_enqueue_scripts', 'ahlbtech_login_logo' ); ?> Displays a custom Dashboard Widget This function supports to customised widget in dashboard. function ahlbtech_custom_dashboard_widgets() { global $wp_meta_boxes; wp_add_dashboard_widget('custom_help_widget', 'Theme Support', 'ahlbtech_custom_dashboard_help'); } function ahlbtech_custom_dashboard_help() { echo ' Custom dashboard widget via functions.php '; } add_action('wp_dashboard_setup', 'ahlbtech_custom_dashboard_widgets'); ?> Allow different file formats in Media Library As you know WP supports some kinds of type format when uploading and downloading process is executed. Moreover, this function will help your website to increase supportive WP function in upload and download activities. In addition, you want to upload special file formats to your WordPress library and get an error message? Then use this code and your problem is solved. The code allows the upload of the file formats ZIP , MOBI , PDF and EPUB . If you need more formats, you will find here the complete list of MIME types . /** * Add further Mime types for the download of the products */ function add_custom_mime_types($mimes){ $new_file_types = array ( 'zip' => 'application/zip', 'mobi' => 'application/x-mobipocket-ebook', 'pdf' => 'application/pdf', 'epub' => 'application/epub+zip' ); return array_merge($mimes,$new_file_types); } add_filter('upload_mimes','add_custom_mime_types'); ?> Turn Off your self-referring Pingbacks Pingbacks and trackbacks are not bad features, tell them whether your articles have been referenced or linked to other websites.  Unfortunately, WordPress has the bad ability to inform you about links to your articles on your own website. So you turn off these annoying news. Ping-backs affect negatively your SEO and also speed of loading your website. If you can disable it, you can enhance your speed loading of your website. function ahlbtech_no_self_ping( &$links ) { $home = get_option( 'home' ); foreach ( $links as $l => $link ) if ( 0 === strpos( $link, $home ) ) unset($links); } add_action( 'pre_ping', 'ahlbtech_no_self_ping' ); ?> Inject Post Images Into the RSS Feed By default, WordPress does not include post pictures in the RSS feed. That's the way you can add post images into RSS Feed. /** * Add Post Images to the RSS Feed */ function ahlbtech_featuredtoRSS($content) { global $post; if ( has_post_thumbnail( $post->ID ) ){ $content = ' ' . get_the_post_thumbnail( $post->ID, 'large', array( 'style' => 'margin-bottom: 15px;' ) ) . ' ' . $content; } return $content; } add_filter('the_excerpt_rss', 'ahlbtech_featuredtoRSS'); add_filter('the_content_feed', 'ahlbtech_featuredtoRSS'); ?> Responsive Videos – YouTube and Vimeo If your theme does not support responsive videos, then you can quickly set support for it yourself. A PHP function ensures an automatic embedding in a Div, the CSS specifications ensure the optimal scaling at every resolution. function ahlbtech_wrap_oembed( $html ){ $html = preg_replace( '/(width|height)="\d*"\s/', "", $html ); // Strip width and height #1 return' '.$html.' '; // Wrap in div element and return #3 and #4 } add_filter( 'embed_oembed_html','ahlbtech_wrap_oembed',10,1); ?> .embed-responsive.embed-responsive-16by9 { position: relative; padding-bottom: 56.25%; /* 16:9 */ padding-top: 25px; height: 0; } .embed-responsive.embed-responsive-16by9 iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } /* This indication makes HTML5 videos responsive */ video { width: 100% !important; height: auto !important; } Custom Sidebars This function supports you to customised sidebars area. function custom_sidebar_widgets_init() { //copy from HERE register_sidebar( array( 'name' => esc_html__( 'Sidebar', 'humescores' ), 'id' => 'sidebar-1', 'description' => esc_html__( 'Add widgets here.', 'humescores' ), 'before_widget' => '', 'after_widget' => '', 'before_title' => '
', 'after_title' => '
', ) ); //to HERE } add_action( 'widgets_init', 'custom_sidebar_widgets_init' ); ?> Modifies tag cloud widget arguments to have all tags in the widget same font size function blog_widget_tag_cloud_args( $args ) { $args = 1; $args = 1; $args = 'em'; return $args; } add_filter( 'widget_tag_cloud_args', 'blog_widget_tag_cloud_args' ); ?> Expanding Your User Profile With Further Social Media Accounts The biographical details in your WordPress profile are quite meager. You do not have many options to link to all your social networks. With this code, you can add any of your social media accounts and quickly view them in the theme. /** * Managing contact fields for author bio */ $ahlbtech_pro_Contactfields = new ahlbtech_pro_Contactfields( // Missing accounts can easily be added array ( 'Feed', 'Twitter', 'Facebook', 'GooglePlus', 'Flickr', 'Xing', 'Github', 'Instagram', 'LinkedIn', 'Pinterest', 'Vimeo', 'Youtube' ) ); class ahlbtech_pro_Contactfields { public $new_fields , $active_fields , $replace ; /** * @param array $fields New fields: array ('Twitter', 'Facebook') * @param bool $replace Replace default fields? */ public function __construct($fields, $replace = TRUE) { foreach ( $fields as $field ) { $this->new_fields = $field; } $this->replace = (bool) $replace; add_filter('user_contactmethods', array( $this, 'add_fields' ) ); } /** * Changing contact fields * @param $original_fields Original WP fields * @return array */ public function add_fields($original_fields) { if ( $this->replace ) { $this->active_fields = $this->new_fields; return $this->new_fields; } $this->active_fields = array_merge($original_fields, $this->new_fields); return $this->active_fields; } /** * Helper function * @return array The currently active fields. */ public function get_active_fields() { return $this->active_fields; } } ?> $twitter = get_the_author_meta( 'twitter', $post->post_author ); $facebook = get_the_author_meta( 'facebook', $post->post_author ); echo 'Twitter | Facebook'; ?> Make Post Images Mandatory add_action('save_post', 'evolution_check_thumbnail'); add_action('admin_notices', 'evolution_thumbnail_error'); function evolution_check_thumbnail($post_id) { // change to any custom post type if(get_post_type($post_id) != 'post') return; if ( !has_post_thumbnail( $post_id ) ) { // set a transient to show the users an admin message set_transient( "has_post_thumbnail", "no" ); // unhook this function so it doesn't loop infinitely remove_action('save_post', 'evolution_check_thumbnail'); // update the post set it to draft wp_update_post(array('ID' => $post_id, 'post_status' => 'draft')); add_action('save_post', 'evolution_check_thumbnail'); } else { delete_transient( "has_post_thumbnail" ); } } function evolution_thumbnail_error() { // check if the transient is set, and display the error message if ( get_transient( "has_post_thumbnail" ) == "no" ) { echo " You have to assign a post image. Without a post image, the article can't be published. "; delete_transient( "has_post_thumbnail" ); } } ?> Change the Look of the First Paragraph /** * Auto-Highlighting - Automatic highlighting of a post's first paragraph * @author Andreas Hecht */ function tb_first_paragraph_highlight( $content ) { return preg_replace( '//', '', $content, 1 ); } add_filter( 'the_content', 'tb_first_paragraph_highlight' ); ?> /*----If you want only change in a single post----*/ .single p.opener { color: #165a72; font-weight: 400; font-size: 21px; line-height: 1.5; } /*-----------If you want only change in a single post & pages----------*/ .single p.opener, .page p.opener { color: #165a72; font-weight: 400; font-size: 21px; line-height: 1.5; } Load the Entire JavaScript in the Footer /** * @uses wp_head() and wp_enqueue_scripts() * */ if ( !function_exists( 'evolution_footer_scripts' ) ) { function evolution_footer_scripts() { remove_action('wp_head', 'wp_print_scripts'); remove_action('wp_head', 'wp_print_head_scripts', 9); remove_action('wp_head', 'wp_enqueue_scripts', 1); } } add_action( 'wp_enqueue_scripts', 'evolution_footer_scripts' ); ?> Create a Breadcrumb Navigation Without a Plugin // Copy from here function ah_the_breadcrumb() { echo ' '; if (!is_home()) { echo ' '; echo 'Home'; echo " "; if (is_category() || is_single()) { echo ' '; the_category(' '); if (is_single()) { echo " "; the_title(); echo ' '; } } elseif (is_page()) { echo ' '; echo the_title(); echo ' '; } } elseif (is_tag()) {single_tag_title();} elseif (is_day()) {echo" Archive for "; the_time('F jS, Y'); echo' ';} elseif (is_month()) {echo" Archive for "; the_time('F, Y'); echo' ';} elseif (is_year()) {echo" Archive for "; the_time('Y'); echo' ';} elseif (is_author()) {echo" Author Archive"; echo' ';} elseif (isset($_GET) && !empty($_GET)) {echo " Blog Archives"; echo' ';} elseif (is_search()) {echo" Search Results"; echo' ';} echo ' '; } ?> Related posts filtered by Category, Use in Single.php if ( ! function_exists( 'evolution_related_posts' ) ) : function evolution_related_posts() { global $post; if($post) { $post_id = get_the_ID(); } else { $post_id = null; } $orig_post = $post; $categories = get_the_category($post->ID); if ($categories) { $category_ids = array(); foreach($categories as $individual_category) $category_ids = $individual_category->term_id; $args=array( 'category__in' => $category_ids, 'post__not_in' => array($post->ID), 'posts_per_page'=> 3, // Number of related posts that will be shown. 'ignore_sticky_posts'=>1 ); $my_query = new wp_query( $args ); if( $my_query->have_posts() ) { echo ' '; echo ' '; _e('Related Posts','evolution'); echo ' '; echo ' '; $c = 0; while( $my_query->have_posts() ) { $my_query->the_post(); $c++; if( $c == 3) { $style = 'third'; $c = 0; } else $style=''; ?> echo ' ' . esc_html( $categories->name ) . ''; } ?> } echo ' '; echo ''; } } $post = $orig_post; wp_reset_postdata(); } endif; ?> /*----------ADD CSS-----------*/ .related-posts { display: flex; } .related-posts .entry-title { font-size: 1rem; } .related-posts .cat { color: #ba9e30; font-size: 0.85rem; } .related-posts .entry-item { width: 31%; margin-right: 3.5%; position: relative; float: left; } .related-posts .entry-item.third { margin-right: 0; } .related-posts a img:hover { opacity: .85; } .entry-related { padding-bottom: 10px; border-bottom: 1px solid #ddd; margin-bottom: 20px } .related-wrap { margin-bottom: 70px; } Hide Plugin from dashboard. Place in functions.php, replace path from edit plugins pathname. function hide_plugin_ahlbtech() { global $wp_list_table; $hidearr = array('really-simple-ssl/rlrsssl-really-simple-ssl.php'); $myplugins = $wp_list_table->items; foreach ($myplugins as $key => $val) { if (in_array($key,$hidearr)) { unset($wp_list_table->items); } } } add_action('pre_current_active_plugins', 'hide_plugin_ahlbtech'); ?> 'really-simple-ssl/rlrsssl-really-simple-ssl.php' is an example of 1 plugin. You can add more plugins that you want to hide when visitors use "view source from browsers like Chrome or FF. The first part before "/" is the plugin folder and after "/" is the core file of your plugin .php. Ex: " array('really-simple-ssl/rlrsssl-really-simple-ssl.php' , "socialshare/socialshare.php" , ....); " Hide Username & Administrator count. Place in functions.php function hide_user_count(){ ?> table.wp-list-table tr#user-9, .subsubsub li.administrator span.count{display: none;} } Remove Inline Styles of WordPress Tag Cloud The WordPress Tag Cloud is the popular widget for our website. Therefore, using this widget, your visitors can find what they are looking for faster. However, WordPress displays tags in different sizes, which is not always a desired property of this widget.  Thus, using this snippet, you can remove the inline styles or you can use CSS to hide its style. function drweb_remove_tagcloud_inline_style($input){ return preg_replace('/ style=("|\')(.*?)("|\')/','',$input); } add_filter('wp_generate_tag_cloud', 'drweb_remove_tagcloud_inline_style',10,1); ?> Turn off WordPress emojis The colourful emojis are not for everyone. In contrast, If you do not want to use emojis in your posts, you can disable this feature completely. The performance of your blog will be better. /** * Disable the emoji's */ function disable_emojis() { remove_action( 'wp_head', 'print_emoji_detection_script', 7 ); remove_action( 'admin_print_scripts', 'print_emoji_detection_script' ); remove_action( 'wp_print_styles', 'print_emoji_styles' ); remove_action( 'admin_print_styles', 'print_emoji_styles' ); remove_filter( 'the_content_feed', 'wp_staticize_emoji' ); remove_filter( 'comment_text_rss', 'wp_staticize_emoji' ); remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' ); add_filter( 'tiny_mce_plugins', 'disable_emojis_tinymce' ); add_filter( 'wp_resource_hints', 'disable_emojis_remove_dns_prefetch', 10, 2 ); } add_action( 'init', 'disable_emojis' ); /** * Filter function used to remove the tinymce emoji plugin. * * @param array $plugins * @return array Difference betwen the two arrays */ function disable_emojis_tinymce( $plugins ) { if ( is_array( $plugins ) ) { return array_diff( $plugins, array( 'wpemoji' ) ); } else { return array(); } } /** * Remove emoji CDN hostname from DNS prefetching hints. * * @param array $urls URLs to print for resource hints. * @param string $relation_type The relation type the URLs are printed for. * @return array Difference betwen the two arrays. */ function disable_emojis_remove_dns_prefetch( $urls, $relation_type ) { if ( 'dns-prefetch' == $relation_type ) { /** This filter is documented in wp-includes/formatting.php */ $emoji_svg_url = apply_filters( 'emoji_svg_url', 'https://s.w.org/images/core/emoji/2/svg/' ); $urls = array_diff( $urls, array( $emoji_svg_url ) ); } return $urls; } ?> Turn off the jQuery Migrate Script jQuery Migrate is a script intended to provide backward compatibility with older jQuery applications. However, the "old" and new jQuery version no longer supports all old applications. Furthermore, this case will certainly not affect more than 5% of all WordPress sites, and yet the not-so-small script will be set default to WordPress. Therefore, this is how you switch it off: /** * jQuery Migrate Script in WordPress. */ if ( ! function_exists( 'evolution_remove_jquery_migrate' ) ) : function evolution_remove_jquery_migrate( &$scripts) { if(!is_admin()) { $scripts->remove( 'jquery'); $scripts->add( 'jquery', false, array( 'jquery-core' ), '1.12.4' ); } } add_filter( 'wp_default_scripts', 'evolution_remove_jquery_migrate' ); endif; ?> Turn off WordPress oEmbed function The WordPress version 4.4 brought the new feature "oEmbed" with it, which is primarily intended to be able to embed external articles or pages using a simple link in posts. So, If you do not need this feature or if you are just uncomfortable with your articles being displayed in external articles at any time, simply disable this feature. /** * Disable embeds on init. * * - Removes the needed query vars. * - Disables oEmbed discovery. * - Completely removes the related JavaScript. * * @since 1.0.0 */ function evolution_disable_embeds_init() { /* @var WP $wp */ global $wp; // Remove the embed query var. $wp->public_query_vars = array_diff( $wp->public_query_vars, array( 'embed', ) ); // Remove the REST API endpoint. remove_action( 'rest_api_init', 'wp_oembed_register_route' ); // Turn off oEmbed auto discovery. add_filter( 'embed_oembed_discover', '__return_false' ); // Don't filter oEmbed results. remove_filter( 'oembed_dataparse', 'wp_filter_oembed_result', 10 ); // Remove oEmbed discovery links. remove_action( 'wp_head', 'wp_oembed_add_discovery_links' ); // Remove oEmbed-specific JavaScript from the front-end and back-end. remove_action( 'wp_head', 'wp_oembed_add_host_js' ); add_filter( 'tiny_mce_plugins', 'evolution_disable_embeds_tiny_mce_plugin' ); // Remove all embeds rewrite rules. add_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' ); // Remove filter of the oEmbed result before any HTTP requests are made. remove_filter( 'pre_oembed_result', 'wp_filter_pre_oembed_result', 10 ); } add_action( 'init', 'evolution_disable_embeds_init', 9999 ); /** * Removes the 'wpembed' TinyMCE plugin. * * @since 1.0.0 * * @param array $plugins List of TinyMCE plugins. * @return array The modified list. */ function evolution_disable_embeds_tiny_mce_plugin( $plugins ) { return array_diff( $plugins, array( 'wpembed' ) ); } /** * Remove all rewrite rules related to embeds. * * @since 1.0.0 * * @param array $rules WordPress rewrite rules. * @return array Rewrite rules without embeds rules. */ function evolution_disable_embeds_rewrites( $rules ) { foreach ( $rules as $rule => $rewrite ) { if ( false !== strpos( $rewrite, 'embed=true' ) ) { unset( $rules ); } } return $rules; } /** * Remove embeds rewrite rules on plugin activation. * * @since 1.0.0 */ function evolution_disable_embeds_remove_rewrite_rules() { add_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' ); flush_rewrite_rules( false ); } register_activation_hook( __FILE__, 'evolution_disable_embeds_remove_rewrite_rules' ); /** * Flush rewrite rules on plugin deactivation. * * @since 1.0.0 */ function evolution_disable_embeds_flush_rewrite_rules() { remove_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' ); flush_rewrite_rules( false ); } register_deactivation_hook( __FILE__, 'evolution_disable_embeds_flush_rewrite_rules' ); ?> Remove unnecessary entries from the WordPress header WordPress loads a lot of stuff via the wp_head() hook into the header of WordPress themes. Some of them are very useful, others less. Some things just inflate the website unnecessarily. Here comes a little snippet that clears up a lot. The code below will remove the following from being output through the wp_head hook. Really Simple Discovery (RSD) linkWindows Live Writer linkWordPress generator noticePost relational linksFeed LinksShortlinks /** * AHLBTech add more file formats */ function add_custom_mime_types($mimes){ $new_file_types = array ( 'zip' => 'application/zip', 'mobi' => 'application/x-mobipocket-ebook', 'pdf' => 'application/pdf', 'epub' => 'application/epub+zip' ); return array_merge($mimes,$new_file_types); } add_filter('upload_mimes','add_custom_mime_types'); ?> User login only with e-mail and password Since WordPress Version 4.5, a user login is also possible with an e-mail address and the password. In addition, to annoy hackers and make WordPress a bit safer, you can only sign up with this code using email and password. // AHLBTech //WordPress Authentication remove_filter('authenticate', 'wp_authenticate_username_password', 20); // Authentication with E-Mail und Passwort add_filter('authenticate', function($user, $email, $password){ //Check for empty fields if(empty($email) || empty ($password)){ //create new error object and add errors to it. $error = new WP_Error(); if(empty($email)){ //No email $error->add('empty_username', __('ERROR: Email field is empty.')); } else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ //Invalid Email $error->add('invalid_username', __('ERROR: Email is invalid.')); } if(empty($password)){ //No password $error->add('empty_password', __('ERROR: Password field is empty.')); } return $error; } //Check if user exists in WordPress database $user = get_user_by('email', $email); //bad email if(!$user){ $error = new WP_Error(); $error->add('invalid', __('ERROR: Either the email or password you entered is invalid.')); return $error; } else{ //check password if(!wp_check_password($password, $user->user_pass, $user->ID)){ //bad password $error = new WP_Error(); $error->add('invalid', __('ERROR: Either the email or password you entered is invalid.')); return $error; }else{ return $user; //passed } } }, 20, 3); Stop users from changing their passwords The administration section of WordPress is the heart and the lungs of your website. You always ensure that the passwords given are very strong, so that attacks have no chance. Users, however, like to change the passwords given in very easy to remember and thus cracking variants. You can prevent this successfully! /** * * Stop Users changing password * */ class Password_Reset_Removed { function __construct() { add_filter( 'show_password_fields', array( $this, 'disable' ) ); add_filter( 'allow_password_reset', array( $this, 'disable' ) ); } function disable() { if ( is_admin() ) { $userdata = wp_get_current_user(); $user = new WP_User($userdata->ID); if ( !empty( $user->roles ) && is_array( $user->roles ) && $user->roles == 'administrator' ) return true; } return false; } } $pass_reset_removed = new Password_Reset_Removed(); Show ads after the xx paragraph If you want to earn money with your blog, then you can not avoid the use of advertising. You can use the popular Google Adsense for example. This snippet will display your ad units according to the paragraph you specify. /** * Show ads after the xx paragraph * */ add_filter( 'the_content', 'tb_insert_post_ads' ); function tb_insert_post_ads( $content ) { $ad_code = 'Here comes the promotional code. Either static advertising or Google Adsense.'; if ( is_single() && ! is_admin() ) { // The number before content determines where the code appears. Here after the second paragraph of an article. return tb_insert_after_paragraph( $ad_code, 2, $content ); } return $content; } // Parent Function that makes the magic happen function tb_insert_after_paragraph( $insertion, $paragraph_id, $content ) { $closing_p = ''; $paragraphs = explode( $closing_p, $content ); foreach ($paragraphs as $index => $paragraph) { if ( trim( $paragraph ) ) { $paragraphs .= $closing_p; } if ( $paragraph_id == $index + 1 ) { $paragraphs .= $insertion; } } return implode( '', $paragraphs ); } ?> View category list with RSS feeds Sometimes it can be handy to see all categories with the associated RSS feed addresses. It gets even better if you can use a WordPress shortcode to display the list everywhere - even in the text widgets. function tb_categories_with_feed() { $args = array( 'orderby' => 'name', 'feed' => 'RSS', 'echo' => false, 'title_li' => '', ); $string .= ' '; $string .= wp_list_categories($args); $string .= ' '; return $string; } // add shortcode add_shortcode('categories-feed', 'tb_categories_with_feed'); // Add filter to execute shortcodes in text widgets add_filter('widget_text', 'do_shortcode'); //------How to add ShortCode +The shortcode: lets you show the list where you want it. It also works within widgets. +In your theme, you can also use the shortcode:
Conclusion
I hope you have discovered some useful snippets of code for you and your WordPress. These functions have been used for our website. Therefore, I can ensure the codes are work like a charm without errors. If you need question, you can add to comments section below for our support. Read the full article
0 notes