Last active
December 7, 2023 09:55
-
-
Save josanua/2bfcaceff35ddc13dcf08bde5d837f73 to your computer and use it in GitHub Desktop.
js scripts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Load DOM Basic usage | |
window.addEventListener('DOMContentLoaded', (event) => { | |
console.log('DOM fully loaded and parsed'); | |
}); | |
// Window Location | |
window.location.href // returns the href (URL) of the current page | |
window.location.hostname // returns the domain name of the web host | |
window.location.pathname // returns the path and filename of the current page | |
window.location.protocol // returns the web protocol used (http: or https:) | |
window.location.assign() // loads a new document --> window.location.assign('<?= $the_permalink_data ?>'); | |
// Reload Page | |
location.reload() | |
// Read and return selected option value | |
function changeOption(){ | |
var sel = document.getElementById('mySelect').selectedIndex, | |
options = document.getElementById('mySelect').options; | |
alert('Selected option ' + options[sel].text); | |
} | |
// Add disabled attribute | |
document.getElementById("unsubscribe-form-button").disabled = true; | |
// Wait for Dom Load | |
document.addEventListener("DOMContentLoaded"function(event) {}) | |
// Go back btn | |
https://www.w3schools.com/jsref/met_his_go.asps | |
<a onclick="goBack()" id="go_back_btn"> | |
{/* <img src="<?php echo get_stylesheet_directory_uri() ?>/images/go_back_btn.svg" alt=""> */} | |
</a> | |
<script> | |
function goBack() { | |
window.history.back(); | |
} | |
</script> | |
// --- work strings --- // | |
// Function for truncate long string and add '...' dots in the end | |
// ideea https://stackoverflow.com/questions/53386455/how-to-toggle-truncate-text-in-javascript/53386545 | |
function text_truncate(str, length, ending) { | |
if (length == null) { | |
length = 100; | |
} | |
if (ending == null) { | |
ending = '...'; | |
} | |
if (str.length > length) { | |
return str.substring(0, length - ending.length) + ending; | |
} else { | |
return str; | |
} | |
}; | |
// truncate text | |
let textString = 'I have been working with Precision Images for a little over 3 years now. I have been using their services for work, and they are ALWAYS SPEEDY! I think I’ve only ever had one issue with a print, and I gave them a call and had it corrected right away! I have also contacted them for a personal print and they were quick to respond and give me a quote. I really appreciate a business who cares (it doesn’t hurt that they’re amazing and super fast either!)'; | |
function text_truncate(str, length, ending) { | |
if (length == null) { | |
length = 100; | |
} | |
if (ending == null) { | |
ending = '...'; | |
} | |
if (str.length > length) { | |
return str.substring(0, length - ending.length) + ending; | |
} else { | |
return str; | |
} | |
}; | |
let finalString = text_truncate(textString, 100); | |
console.log(finalString); | |
// clear string form whitespace | |
const stripped = ' My String With A Lot Whitespace '.replace(/\s+/g, '') | |
str.trim(); | |
//replace white space with "-" | |
.replace(/ /g,"-") | |
// change charactes, work replace | |
let string = "0-5"; | |
function formatEstimatedValues(rawValue = '') { | |
let formatedValue = ''; | |
if (rawValue !== '') { | |
let needToFormatValue = rawValue; | |
formatedValue = needToFormatValue.replace("-", " - ").toString(); | |
} else { | |
console.log('Error on formating Value: No Value'); | |
} | |
return formatedValue; | |
} | |
console.log(formatEstimatedValues(string)); | |
// Groups checkboxes with the Same Name, same name checkbox group | |
https://www.dyn-web.com/tutorials/forms/checkbox/same-name-group.php | |
// generate random characters, generate char, generate text | |
function randomStringId() { | |
let chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; | |
let string_length = 12; | |
let randomstring = ''; | |
for (var i = 0; i < string_length; i++) { | |
var rnum = Math.floor(Math.random() * chars.length); | |
randomstring += chars.substring(rnum,rnum+1); | |
} | |
return randomstring; | |
} | |
{/* get site url*/} | |
https://www.w3schools.com/js/js_window_location.asp | |
document.URL | |
> "http://example.com/page1.html" | |
document.location.href | |
> "http://example.com/page1.html" | |
document.location.pathname | |
> "/page1.html" | |
document.location.origin | |
> "http://example.com" | |
window.location.href returns the href (URL) of the current page | |
window.location.hostname returns the domain name of the web host | |
window.location.pathname returns the path and filename of the current page | |
window.location.protocol returns the web protocol used (http: or https:) | |
window.location.assign() loads a new document | |
{/* change the url in Address Bar without refreshing the page in JavaScript. */} | |
{/* https://developer.mozilla.org/en-US/docs/Web/API/History/pushState */} | |
window.history.pushState(“object or string”, “Title”, “/new-url”); | |
window.history.replaceState(“object or string”, “Title”, “/another-new-url”); | |
// How to check if element has class, contain class | |
const element = document.querySelector("#box"); | |
element.classList.contains("active"); | |
// find and change url link, change link | |
https://www.denisbouquet.com/change-url-parameters-without-page-reload-replacestate-javascript/ | |
// How to Change href link using JavaScript? | |
var newURL = "https://youtube.com"; | |
document.getElementById("link").href = newURL; | |
// my code | |
if (document.getElementsByClassName('logged-in').length > 0) { | |
const topMenuFirstBtnURL = 'https://portal-v2.kickjobs.com/auth/register/'; // https://portal.kickjobs.com/auth/register/ | |
const topMenuLoginBtnBtnURL = 'https://portal-v2.kickjobs.com/auth/login'; // https://portal.kickjobs.com/auth/login | |
document.querySelector('.big-dark-blue-btn.for-changing-link a').href = topMenuFirstBtnURL; | |
document.querySelector('.log-in-btn.for-changing-link a').href = topMenuLoginBtnBtnURL; | |
if(document.getElementsByClassName('single-job-column').length > 0) { | |
// example https://portal.kickjobs.com/jobs/45?apply=true | |
// document.querySelector('.single-job-column a.dark-button').href = topMenuLoginBtnBtnURL; | |
let firstLinkValue = document.querySelector('.single-job-column a.dark-button').href; | |
let newLinkString = firstLinkValue.replace(/kickjobs/g, "portal-v2"); | |
console.log("1: " + newLinkString); | |
document.querySelector('.single-job-column a.dark-button').href = newLinkString; | |
console.log("2 chagend: " + document.querySelector('.single-job-column a.dark-button').href); | |
} | |
} | |
{/* popup after time and save state in localstorage, load popup after time */} | |
https://www.py4u.net/discuss/942975 | |
My Code | |
// Marketing popup type | |
// After a user visits the page for 30 seconds, a pop-up shows up asking for a newsletter subscription (e-mail) | |
// Info is saved in local storage | |
document.addEventListener("DOMContentLoaded", function (event) { | |
jQuery(document).ready(function ($) { | |
// console.log('hi') | |
// set/get needed values | |
let localStorageStateValue = ''; | |
// declare show popup function | |
function show_marketing_popup() { | |
// alert('Popup'); | |
$('.home-popup').fadeIn(500); | |
// $('.close-popup-btn').click(function() { | |
// $('.popup').fadeOut(300); | |
// }); | |
} | |
// verify user session state and if need call funcs | |
if (sessionStorage.getItem('userVisitedState') === null) { | |
// call popup after 30 seconds | |
setTimeout(function(){ show_marketing_popup() }, 5000); | |
sessionStorage.setItem("userVisitedState", true); | |
} | |
// example https://www.codegrepper.com/code-examples/javascript/display+a+popup+only+once+per+user | |
// if(localStorage.getItem('popState') != 'shown'){ | |
// $j("#popup").delay(2000).fadeIn(); | |
// localStorage.setItem('popState','shown') | |
// } | |
// | |
// $j('#popup-close, #popup').click(function(e) // You are clicking the close button | |
// { | |
// $j('#popup').fadeOut(); // Now the pop up is hiden. | |
// }); | |
}); // end jquery document ready | |
}); | |
{/* Show popup after some time, */} | |
function show_marketing_popup() { | |
// work with elements | |
document.documentElement.classList.add('js-popup-is-active') | |
document.body.classList.add('js-no-scroll') | |
// conditions for where and which popup need to show | |
if (document.body.classList.contains('tax-job_sectors') || document.body.classList.contains('post-type-archive-employees')) { | |
document.querySelector("[data-popup-id='job-alert-form']").classList.add('is-active'); | |
} else { | |
document.getElementById('marketing-popup').classList.add('is-active') | |
} | |
} | |
// verify user session state and if need do function calls | |
if (sessionStorage.getItem('userMarketingPopupVisitedState') === null) { | |
// need to call popup after 6 seconds | |
setTimeout(function () { | |
show_marketing_popup() | |
}, 6000); | |
sessionStorage.setItem("userMarketingPopupVisitedState", true); | |
} | |
// generate random numbers | |
https://www.joshwcomeau.com/snippets/javascript/random/ | |
Math.floor(Math.random() * (max - min)) + min; | |
//--- DOM collections ---// | |
/* --- Element.classList --- */ | |
// work logics classList | |
if(div.classList.contains('className') { | |
console.log('some text') | |
} | |
elem.addEventListener('click', () => { | |
if(elem.classList.contains('className') { | |
// some actions | |
} else { | |
// another actions | |
} | |
}) | |
//--- Intersting functions problems stuff ---// | |
// -> Functie care primeste array si dubleaza fiecare element in ea. | |
double([1,2,3] -> [2,4,6]); | |
// imperative | |
function double (arr) { | |
let results = []; | |
for (let i = 0; i < arr.length; i++){ | |
results.push(arr[i] * 2) | |
} | |
return results; | |
} | |
// declarative | |
function double (arr) { | |
return arr.map((item) => item * 2) | |
} | |
// -> primeste masiv si intoarce suma tuturor elementelor | |
// imperative | |
function add (arr) { | |
let result = 0 | |
for (let i = 0; i < arr.length; i++){ | |
result += arr[i] | |
} | |
return result | |
} | |
// declarative | |
function add (arr) { | |
return arr.reduce((prev, current) => prev + current, 0) | |
} | |
//--> functiile mele | |
// integer value formater | |
function jobAmountValueFormatter (amount = 0) { | |
if ( Number.isInteger(amount)) { | |
amount = amount + ".00"; | |
} | |
return amount; | |
} | |
// strip HTML tags | |
function stripHTMLTags(originalString= '') { | |
const regex = /(<([^>]+)>)/gi; | |
let strippedString = ''; | |
if (originalString !== '') { | |
strippedString = originalString.replace(regex, "") | |
} else { | |
console.log ('No "job.short_description" text from API'); | |
} | |
return strippedString; | |
} | |
// check screen resizes, detect screen resize | |
https://webdevetc.com/blog/matchmedia-events-for-window-resizes/ | |
const mediaQuery = '(max-width: 700px)'; | |
const mediaQueryList = window.matchMedia(mediaQuery); | |
mediaQueryList.addEventListener('change', event => { | |
console.log(window.innerWidth); | |
if (event.matches) { | |
console.log('The window is now 700px or under'); | |
} else { | |
console.log('The window is now over 700px'); | |
} | |
}) | |
// trim long number, cut long number | |
https://codingbeautydev.com/blog/javascript-get-length-of-number/ | |
export function trimLongNumber(number = 0) { | |
let str = number.toString(); // convert number to string | |
let result = ''; | |
if (str.length > 6) { | |
str = str.substring(0,6); // cut six first character | |
result = parseInt(str); // convert it to a number | |
} else { | |
result = number; | |
} | |
return result; | |
} | |
// Draw pyramid, for loop | |
let result = ''; | |
const length = 7; | |
for (let i = 1; i < length; i++) { | |
for (let j = 0; j < i; j++) { | |
result += "*"; | |
} | |
result += '\n'; | |
} | |
console.log(result); | |
// Create a MediaQueryList object | |
// work with screen width | |
<div class="cta-slider bg-container" | |
style="background-image:url()" | |
data-bg-mob-img="" | |
</div> | |
const mobileSize = window.matchMedia("(max-width: 520px)"); | |
const sliderImgBg = document.querySelectorAll('.bg-container'); | |
if (mobileSize.matches) { | |
console.log('activated'); | |
for (let i = 0; i < sliderImgBg.length; i++) { | |
bgMobImgUrl = sliderImgBg[i].dataset.bgMobImg; | |
sliderImgBg[i].attributes.style.nodeValue = "background-image:url(" + bgMobImgUrl + ")"; | |
} | |
} | |
mobileSize.addEventListener("change", function () { | |
if (mobileSize.matches) { | |
console.log('activated'); | |
for (let i = 0; i < sliderImgBg.length; i++) { | |
bgMobImgUrl = sliderImgBg[i].dataset.bgMobImg; | |
sliderImgBg[i].attributes.style.nodeValue = "background-image:url(" + bgMobImgUrl + ")"; | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment