Reputation: 1111
Is there a way to fire jquery only once when resizing? I have here a script that adds a hash(#)
within the href
of an anchor <a>
element. The problem is the script keeps when resizing and so it keeps adding hash
within the href
. Is there a way to make it fire only once?
(function($){
'use strict';
var mobileMenuDrawer = {
init : function() {
$('.region-primary-menu').addClass('primary-mobile-menu');
$('.primary-mobile-menu .menu.-primary > .menu-item').addClass('mobile-menu-item');
$('.primary-mobile-menu .menu.-primary > .mobile-menu-item > .link').off('click').on('click', function() {
$(this).closest('.mobile-menu-item').toggleClass('-active');
})
},
clear : function() {
$('.primary-mobile-menu, .mobile-menu-item').removeClass('primary-mobile-menu mobile-menu-item');
}
}
var addHash = {
init : function() {
if ($('.region-primary-menu').hasClass('primary-mobile-menu')) {
$('.primary-mobile-menu .mobile-menu-item > .link').each(function() {
// console.log($(this).attr('href'));
let currentUrl = $(this).attr('href');
$(this).prop('href', '#' + currentUrl);
// this.href = '/#/' + this.href;
// window.location.hash = $(this).attr('href');
});
}
else {
$('.primary-mobile-menu .mobile-menu-item > .link').each(function() {
$(this).removeAttr('#');
});
}
}
}
$(document).ready(function() {
if ($(window).outerWidth() <= 1024) {
mobileMenuDrawer.init();
}
else {
mobileMenuDrawer.clear();
}
addHash.init();
});
$(window).on('resize', function() {
if ($(window).outerWidth() <= 1024) {
mobileMenuDrawer.init();
addHash.init();
}
else {
mobileMenuDrawer.clear();
}
});
})(jQuery)
Upvotes: 2
Views: 46
Reputation: 4650
Yes. Just put a flag checking if the property already exists:
if(!$(this).prop('href')) {
$(this).prop('href', '#' + currentUrl);
}
Or if the property is similar:
if($(this).prop('href') != '#' + currentUrl) {
$(this).prop('href', '#' + currentUrl);
}
Or if the property is empty (will only work if the property already exists):
if($(this).prop('href') == "") {
$(this).prop('href', '#' + currentUrl);
}
If you want to prevent the entire codeblock from executing. You could use some sort of custom flag that you need to flick to the opposite boolean value once a desired operation has been completed. You could make this a variable in your local function scope or make it a property of the addHash
object. I'll do the former in this one.
let isOk = false;
var addHash = {
init : function() {
if(isOk) return;
if ($('.region-primary-menu').hasClass('primary-mobile-menu')) {
$('.primary-mobile-menu .mobile-menu-item > .link').each(function() {
let currentUrl = $(this).attr('href');
$(this).prop('href', '#' + currentUrl);
isOk = true;
});
}
}
}
Note: You should stop using var.
Upvotes: 2