Skip to content

Instantly share code, notes, and snippets.

@josanua
Last active April 1, 2024 10:18
Show Gist options
  • Save josanua/fe8180e9181b15c2ba4b1b071f991f30 to your computer and use it in GitHub Desktop.
Save josanua/fe8180e9181b15c2ba4b1b071f991f30 to your computer and use it in GitHub Desktop.
jQuery
http://jquery.com/
// Inlude and Test if jQuery Work
http://learn.jquery.com/using-jquery-core/document-ready/
http://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/
3.x:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
2.x:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
1.x:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
// jQuery UI http://jquerymobile.com
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"></link>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>;
// Detect jquery version, detect version.
$().jquery;
jQuery().jquery;
jQuery.fn.jquery;
// --- Initialization, load code after all stuff is loaded --- //
// good to read https://www.freecodecamp.org/news/javascript-document-ready-jquery-example/
// js load script
window.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM fully loaded and parsed');
});
// Standard.
// prevent any jQuery code from running before the document is finished loading (is ready).
// Shorter version, Shortcut for ready()
// shorter version,
// recommended way of calling:
// here for compatibility
jQuery(function(){
console.log( "ready!" );
});
jQuery(function ($) {
});
// or
// recommended way of calling:
$(function() {
$( "p" ).text( "The DOM is now loaded and can be manipulated." );
});
// alternative with load but it waits for image and iframes loading
jQuery(window).load(function () {
console.log('The page and all its assets are loaded!')
});
$(window).load(function () {});
// load wait for all documents script and images, iframes to load
// better to use ready!
// better to use ready
// The .ready() method offers a way to run JavaScript code as soon as the page's Document Object Model (DOM) becomes safe to manipulate
$( handler )
$( document ).ready( handler )
$( "document" ).ready( handler )
$( "img" ).ready( handler )
$().ready( handler )
// As of jQuery 3.0, only the first syntax is recommended
$( handler )
//
$( document ).ready(function() {
// Handler for .ready() called.
});
$(function() {
$( "p" ).text( "The DOM is now loaded and can be manipulated." );
});
// Prevent load jquery twice
// load jQuery, if not loaded before
if (!JFactory::getApplication()->get('jquery')) {
JFactory::getApplication()->set('jquery', true);
// add jQuery
}
// --- vanilla JS Dom Load and apply jQuery, include jquery --//
document.addEventListener("DOMContentLoaded", function(event) {
jQuery(function($){
$("a.page-numbers").removeClass("page-numbers").addClass("pagination_item_url");
$(".prev, .next").addClass("btns");
console.log('script works')
});
});
// debuging events
console.log(document.readyState);
// --- Include jQuery in Wordpress --- //
// By default when you enqueue jQuery in Wordpress you must use jQuery, and $ is not used (this is for compatibility with other libraries).
// Your solution of wrapping it in function will work fine, or you can load jQuery some other way (but that's probably not a good idea in Wordpress).
// If you must use document.ready, you can actually pass $ into the function call:
// jQuery(function ($) { ... } or this:
// ;(function($){your code})(jQuery);
// Working method !!!
(function($) {
// $ Works! You can test it with next line if you like
// console.log($);
})( jQuery );
// Another example
jQuery(function($){ ...your code... });
// Working to, for document.ready option
// Write this if you need it in header
jQuery(document).ready(function( $ ) {
// $ Works! You can test it with next line if you like
// console.log($);
});
// --- work Selectors --- //
https: //api.jquery.com/jQuery/
https: //www.w3schools.com/jquery/jquery_ref_selectors.asp
https://learn.jquery.com/using-jquery-core/selecting-elements/
/* If no elements match the provided selector, the new jQuery object is "empty"; that is, it contains no elements and has.length property of 0. */
Basic syntax: $(selector).action();
$("*") // Selects all elements
$(this) // Selects the current HTML element, does not run a DOM query, work in context
$("p.intro") // Selects all <p> elements with class="intro"
$("p:first") // Selects the first <p> element
$("ul li:first") // Selects the first <li> element of the first <ul>
$("ul li:first-child") // Selects the first <li> element of every <ul>
$("[href]") // Selects all elements with an href attribute
$("a[target='_blank']") // Selects all <a> elements with a target attribute value equal to "_blank"
$("a[target!='_blank']") // Selects all <a> elements with a target attribute value NOT equal to "_blank"
$("[attribute='value']") // Select atributes,
$(":button") // Selects all <button> elements and <input> elements of type="button"
$("tr:even") // Selects all even <tr> elements
$("tr:odd") // Selects all odd <tr> elements
$("div ~ p") // Select all <p> elements that are siblings and appear after the <div> element
$("div + p") // The <p> element that are next to each <div> elements
$(":root") // The :root selector selects the document's root element.
$("div:has(p)") // All <div> elements that have a <p> element
// combinated selectors
$('h3:has(span)'); // <h3>Lorem <span>Lorem</span></h3>
$('.block:parent'); // parent block with class .block
$('.block:empty'); // parent empty block with class .block
// childrens / parents selectors , Tree Traversal
https://api.jquery.com/category/traversing/tree-traversal/
$('selector').parent();
$('selector').children();
$('selector').closest();
$('selector').next();
$('selector').prev();
$('selector').siblings();
// optimised versions example, for easy understanding
// general
$(".content a.button");
// better version to write
$("a.button", "content");
$("content").find("a.button"); // best version to understand after a while
let $content = $(".content");
$content.find("a.button");
$content.find("h3.title");
// You can use the find() method to get the children of the $(this) selector using jQuery.
https://api.jquery.com/find/#find-selector
// read data atribute value, take data value, get data atribute value
.data( "orig-name" ); // if data-orig-name
// example
<span id="work_data" data-tax-name="magazin_agricol"></span>
Query('#work_data').data( "tax-name" );
$('#work_data').data( "tax-name" );
// Iteration for selecting elements or context, each() method
each() // Using .each() when implicit iteration is not enough
$('div').each(function () {
// "this" is each element in the wrapper set.
console.log(this.id);
});
// Testing selection
// Doesn't work!
if ( $( "div.foo" ) ) {
...
}
// Testing whether a selection contains elements.
if ( $( "div.foo" ).length ) {
...
}
// --- Event Methods, work context --- //
// An event represents the precise moment when something happens.
https://www.w3schools.com/jquery/jquery_events.asp (doc)
https://www.w3schools.com/jquery/jquery_ref_events.asp (ref)
// prevent default
e.preventDefault();
// assign a click event
// deprecated
$("p").click(function () {
// action goes here!!
});
$("p").on('click', function () { // best method to use then use AJAX or reload some elements
// action goes here!!
});
// example for click on form button, click button, click btn
jQuery('#content').on('click', function (e) {
e.preventDefault();
});
// use this in context, work context
$('#selector').on('click', function (e) {
let $this = $(e.currentTarget);
e.preventDefault($this);
});
// Commonly Used jQuery Event Methods
// Full list of events https://api.jquery.com/category/events/ . list events
$(document).ready()
click()
dblclick()
mouseenter()
mouseleave()
mousedown() // the function is executed, when the left, middle or right mouse button is pressed down, while the mouse is over the HTML element:
mouseup() // button is released, while the mouse is over
change() // attaches/Triggers the change event
hover()
focus()
blur()
on() // the on() method attaches one or more event handlers for the selected elements
// Attach multiple event handlers to a <p> element:
$("p").on({
mouseenter: function () {
$(this).css("background-color", "lightgray");
},
mouseleave: function () {
$(this).css("background-color", "lightblue");
},
click: function () {
$(this).css("background-color", "yellow");
}
});
// --- Set Content - text(), html(), and val(), Change content values, change text, change values --- //
text() - Sets or returns the text content of selected elements
html() - Sets or returns the content of selected elements (including HTML markup)
val() - Sets or returns the value of form fields
// example
// Change content values, change text, change values, click functions
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
// --- Examples --- //
// Sticky header
// https://codepen.io/JGallardo/pen/lJoyk
$(window).scroll(function() {
if ($(window).scrollTop() >= 60) {
$('#ng-custom-topmenu').addClass( 'fixed-ng-custom-topmenu' );
}
else { $('#ng-custom-topmenu').removeClass('fixed-ng-custom-topmenu'); }
});
// Validation plugin https://jqueryvalidation.org/
// Experiment for Send AJAX request and validate work without input:type=submit
$(document).ready(function(){
$('#button_id').click( function() {
if ($("#some_form").validate().form() == true)
{
// Call Ajax Here
}
});
});
// --- work AJAX --- //
ajax();
// Example
$.ajax({
url: "<?php echo get_stylesheet_directory_uri(); ?>/pdf-generator/pdfController.php",
cache: false, // By default, the ajax() and load() AJAX functions both use the GET HTTP protocol.
type: 'POST',
data: {
// generatePdf: tableValues,
},
// dataType: 'html',
complete: function (xhr) {
// console.log('Complete Response: ' + xhr.responseText);
window.open(xhr.responseText);
},
)}
// Send image and data with AJAX
https://forum.jquery.com/topic/upload-file-and-json-data-in-the-same-post-request-using-jquery-ajax
var formData = new FormData();
formData.append('logo', logoImg);
var objArr = [];
objArr.push({"id": id, "name": userName});
//JSON obj
formData.append('objArr', JSON.stringify( objArr ))
$.ajax({
url: url,
type:"POST",
processData:false,
contentType: false,
data: formData,
complete: function(data){alert("success");}
});
// End
// BS3 menu, close after click menu (just put in o the page)
$(document).on('click.nav','.navbar-collapse.in',function(e) {
if( $(e.target).is('a') ) {
$(this).removeClass('in').addClass('collapse');
}
});
// Check if element is loaded
if ( jQuery(".wpb_close_btn").length ) {}
//How to get the values of selected checkboxes in a group using jQuery
https://www.tutorialrepublic.com/faq/how-to-get-the-values-of-selected-checkboxes-in-a-group-using-jquery.php
// Disable attribute
prop( "disabled", true );
// --- jQuery utils --- //
// BS4 Bootstrap 4 multi dropdown navbar
https://bootstrapthemes.co/demo/resource/bootstrap-4-multi-dropdown-navbar/
// --- Bootstrap jQuery --- //
// check jquery version
$.fn.tooltip.Constructor.VERSION
// Events preventDefault() prevent default function
$('#myModal').on('show.bs.modal', function (e) {
if (!data) {
return e.preventDefault() // stops modal from being shown
}
})
// --- Scroll to top --- //
var btn = $('.arrow-up');
$(window).scroll(function() {
if ($(window).scrollTop() > $('.showcase').outerHeight()) {
btn.addClass('show');
} else {
btn.removeClass('show');
}
});
btn.on('click', function(e) {
e.preventDefault();
$('html, body').animate({scrollTop:0}, '300');
});
// .showcase - first div (for take height dimension, .scrollTop() > 100 (another solution)
/* Scroll to top btn */
#scrollBtn {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 9999;
border: none;
outline: none;
background: url("../images/scroll_btn.svg") no-repeat center top;
background-size: contain;
width: 50px;
height: 50px;
cursor: pointer;
}
#scrollBtn.show{
display: block;
})
// --- check if some tag have content--- //
if ($("#showed_only_activity").length){}
// --- change atribut href, href link change, a tag atributem change href --- //
$("a").attr('href', 'http://www.live.com/')
// --- Get size of the window, window size --- //
$(window).width();
$(window).height();
// --- work array's --- //
// clear array from empty elements
arr = arr.filter(function (el) {
return el !== null && el !== "";
});
// --- work forms, work inputs, input values, check input values --- //
// --- Get Values, get input values, get input forms --- //
// check input checkbox, input checking
$('input[type=checkbox]').prop('checked');
if ($(this).prop('checked') === true/false ) {}
if($(this).is(":checked")) {console.log('checked')}
if( $('#el').is(':checked') ){
console.log("Checkbox Is checked");
}
else{
console.log("Checkbox Is not checked");
}
// some of my code
// Contact submission
// take value form mail input and replace in current input field
let checkbox_Idem = $('input[name=financieel_contactperson_facturatie]');
let input_contactperson_email = $('#financieel_contactperson_email');
let text_contactperson_facturatie_email = $('#financieel_contactperson_facturatie_email');
// First checkbox checking
checkbox_Idem.on('change', function () {
// detect checkbox
if ($(this).val() === 'Idem' ) {
// take data from mail.input
if (input_contactperson_email.val() !== '' ) {
// change text.input value
$(text_contactperson_facturatie_email).val(input_contactperson_email.val()).prop('disabled', true);
}
} else {
$(text_contactperson_facturatie_email).val('').prop('disabled', false);
}
});
// Work with mail field in case of editing it with checkbox_Idem checkbox selected
input_contactperson_email.on('change', function () {
// check val and state
if(checkbox_Idem.is(':checked') && checkbox_Idem.val() === 'Idem') {
$(text_contactperson_facturatie_email).val($(this).val());
}
});
// radio button, check radio button, radio input
$("input[name='gender']:checked").val()
// example
$(document).ready(function(){
$("input[type='button']").click(function(){
var radioValue = $("input[name='gender']:checked").val();
if(radioValue){
alert("Your are a - " + radioValue);
}
});
});
// Get value from select, get select value, select list values
<select id="myselect">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
$( "#select-member-type option:selected" ).val(); //Get value
$( "#myselect option:selected" ).text(); //Get text value
// -- Checking to see if the wrapper set is empty, check selected element
// Is there an element in the set?
if ($('a').get(0)) {}
// Check the length of the set. Can also use .size()
if ($('a').length) {}
// get value from radio button, checked input
jQuery('#select-radio-value input:checked').val();
// --- Checkboxes, change event --- //
// inputs, Uncheck All
$('.checkall').on('click', function () {
$(":checkbox").attr("checked", true);
});
// Uncheck All
$('.uncheckall').on('click', function () {
$(":checkbox").attr("checked", false);
});
// example
jQuery(function ($) {
// TODO: de prelucrat, submit pleaca datele oricum
$('input#user_idnp_code').on('change', .on('change', function () {
let input_idnp_value = $(this).val()
console.log(input_idnp_value + ' : ' + input_idnp_value.length)
if (input_idnp_value.length > 13) {
$('#alert-msg-max-num').removeClass('d-none').addClass('d-inline-b')
$('#alert-msg-min-num').removeClass('d-inline-b').addClass('d-none')
}
if (input_idnp_value.length < 13) {
$('#alert-msg-min-num').removeClass('d-none').addClass('d-inline-b')
$('#alert-msg-max-num').removeClass('d-inline-b').addClass('d-none')
}
if (input_idnp_value.length === 13) {
$('#alert-msg-max-num').removeClass('d-inline-b').addClass('d-none')
$('#alert-msg-min-num').removeClass('d-inline-b').addClass('d-none')
}
})
})
// --- work json --- //
// A common use of JSON is to exchange data to/from a web server.
// When receiving data from a web server, the data is always a string.
// Parse the data with JSON.parse(), and the data becomes a JavaScript object.
// https://www.w3schools.com/js/js_json_php.asp
// https://www.w3schools.com/js/js_json_parse.asp
// validator
// https://jsonformatter.curiousconcept.com/#
JSON.stringify() // to convert it into a string.
// --- filters list, list filter --- //
document.addEventListener("DOMContentLoaded", function (event) {
jQuery(document).ready(function ($) {
$("#c-jobs-list-filter").on("keyup", function() {
let text_value = $(this).val().toLowerCase();
$(".facetwp-radio").filter(function() {
$(this).toggle( $(this).text().toLowerCase().indexOf(text_value) > -1 );
});
});
});
});
// --- get list values, get all options of a select --- //
$("#jobs-search-sector option").map(function() {
return $(this).val();
}).get();
// --- slick slider --- //
// detect screen size and adapt slider, adapt slider for mobile screens, slick slider
// https://github.com/kenwheeler/slick/issues/3282
$(window).on('load', () => {
const element = $('.slick-carousel');
const mediaQuery = window.matchMedia('(max-width: 640px)');
const handleSwitchSlick = ((e) => {
if (e.matches) {
element.slick({
infinite: false,
arrows: false,
});
} else if (element.hasClass('slick-initialized')) {
element.slick('unslick');
}
});
mediaQuery.addListener(handleSwitchSlick);
handleSwitchSlick(mediaQuery);
});
// --- stop execution on click --- //
$('selector').click(function(e){
e.stopPropagation();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment