jquery - dynamic menu - click function not working - javascript

I have a horizontal category bar. this is populated by php - i set a data-cat-id property on the anchor. then use a jquery click function to get this value like this:
$('.filterCat').click(function() {
alert('cat id is:'+$(this).data("cat-id"))
return false;
});
This works fine. But the horizontal bar has a function that adds list elements to a "more" sub menu when the width gets smaller than its content. using the code:
$(function() {
alignMenu();
$(window).resize(function() {
$("#horizontal").append($("#horizontal li.hideshow ul").html());
$("#horizontal li.hideshow").remove();
alignMenu();
});
function alignMenu() {
var w = 0;
var mw = $("#horizontal").width() - 150;
var i = -1;
var menuhtml = '';
jQuery.each($("#horizontal").children(), function() {
i++;
w += $(this).outerWidth(true);
if (mw < w) {
menuhtml += $('<div>').append($(this).clone()).html();
$(this).remove();
}
});
$("#horizontal").append(
'<li style="position:relative;" href="#" class="hideshow">' + 'More ' + '<span style="font-size:13px">↓</span>' + '<ul>' + menuhtml + '</ul></li>');
$("#horizontal li.hideshow ul").css("top",
$("#horizontal li.hideshow").outerHeight(true) + "px");
$("#horizontal li.hideshow").click(function() {
$(this).children("ul").toggle();
});
if (menuhtml == '') {
$("#horizontal li.hideshow").hide();
} else {
$("#horizontal li.hideshow").show();
}
}
});
This also works but now when there is a "more" button (because the content is bigger) the click function does not work anymore.
i have made a fiddle - if you click on a normal menu item it shows the alert, but if you click on a item that is places under "more" it does nothing see FIDDLE: https://jsfiddle.net/quosa60e/

For dynamically created elements .click() does not work
document.on('click','SELECTOR',function(){});
So you should use:
$(document).on('click','.filterCat',function() {
alert('cat id is:'+$(this).data("cat-id"))
return false;
});

Related

set view position by element (javascript)

Is there any easy way how to set Y position of the screen by the element?
Tried to do with scrolling but didn't make wanted effect, so maybe setting screen view position would do the trick.
have a div with string:
Function is in use with elementor (wordpress) toggle tabs which generating anchor links for tabs and they making a trick which opens exact tab by link.
<script type="text/javascript">
jQuery(document).ready(function($){
setTimeout(function(){
var current = window.location.href;
var current = current.split('#tab');
if(current.length>1) {
$('.elementor-tab-title').removeClass('elementor-active');
$('.elementor-tab-title[data-tab="'+current[1]+'"]').addClass('elementor-active');
$('.elementor-tab-content').hide();
$('.elementor-tab-content[data-tab="'+current[1]+'"]').show();
}
}, 200);
$('.elementor-tab-title[data-tab]').click(function(){
var current_location = window.location.href;
current_location = current_location.split('#');
window.location = current_location[0]+'#tab'+$(this).attr('data-tab');
})
})
jQuery(document).ready(function ($) {
setTimeout(function () {
var current = window.location.href
var current = current.split('#tab')
if (current.length > 1) {
showAndScrollToTab($, current)
}
}, 200);
// change the browser url according to selected tab
$('.elementor-tab-title[data-tab]').click(function () {
var current_location = window.location.href;
current_location = current_location.split('#')
window.location = current_location[0] + '#tab' + $(this).attr('data-tab')
})
// activate tab also from anchor link in the same page
$('a').on('click', function () {
var anchorUrl = $(this).attr('href')
var anchor = anchorUrl.split('#tab')
if (anchor.length > 1) {
showAndScrollToTab($, anchor)
}
})
})
function showAndScrollToTab($, current) {
// adding class
$('.elementor-tab-title').removeClass('elementor-active')
$('.elementor-tab-title[data-tab="' + current[1] + '"]').addClass('elementor-active')
// scroll to
var customOffset = '20';
$([document.documentElement, document.body]).animate({
scrollTop: $('.elementor-tab-title[data-tab="' + current[1] + '"]').closest('.elementor-widget-container').offset().top - customOffset }, 1000)
}</script>
Html in use for toggle tab headings:
<div class="elementor-toggle-item">
<div id="elementor-tab-title-2287" class="elementor-tab-title elementor-active" data-tab="7" role="tab" aria-controls="elementor-tab-content-2287">
How to modify the function for making device screen view top is 40px to the .elementor-tab-title[data-tab="' + current[1] + '"] div? Is it possible to adjust offset from div element to top by device (mobile, tablet, desktop)?
Any other solutions are welcome how to do that!

Jquery change color of SVG element using jscolor.js is failing

I have a web page in which SVG is embedded. I am pulling references of elements of SVG and creating color swatches for every element using jscolor.js library.
I want to adjust color of these elements using swatches I am dynamically creating on click jquery event listener.
The problem is, after couple of changes SVG element is becoming black due to some error which is assigning 'undefined' fill color to this SVG element.
I am not getting why it not working all the time.
The main function to do this job is as follows
$("#svg_obj").on("click", ".badge", function(event) {
event.stopPropagation();
var rect = event.target.getBoundingClientRect();
$(".badge").attr('selection', null);
this.setAttribute('selection', true);
var svg_left = ((Math.round(this.getAttribute('width')) - Math.round(this.getBoundingClientRect().width)) / 2);
$(".selector").css("left", Math.round(this.getBoundingClientRect().x - svg_left) + 'px')
$(".selector").css("top", Math.round(this.getBoundingClientRect().y) + 'px')
$(".selector").css("width", Math.round(this.getAttribute('width')) + 'px');
$(".selector").css("height", Math.round(this.getAttribute('height')) + 'px');
$(".selector").css("visibility", "visible");
for (let i = 0; i < this.childNodes.length; i++) {
var svg_g = this.childNodes[i];
// console.log(this.childNodes[i].nodeName);
if (svg_g.nodeName == 'g') {
var polygons = Array.from(svg_g.querySelectorAll("polygon"));
var polygons = polygons.concat(Array.from(svg_g.querySelectorAll("path")));
// console.log(polygons);
Object.values(polygons).forEach(val => {
// console.log(val.attributes.fill.value.substring(1));
console.log(val);
$("#status_bar").append("<p class='swatches " + val.attributes.fill.value.substring(1) + "' >Color:<input data-jscolor='{position:"right"}' value='" + val.attributes.fill.value + "'></p>").on('change', '.' + val.attributes.fill.value.substring(1), function() {
val.attributes.fill.value = $('#status_bar .' + val.attributes.fill.value.substring(1)).find('input').val();
console.log($('.' + val.attributes.fill.value.substring(1)).find('input').val());
});
});
} else {
// console.log("Not a group " +svg_g);
}
}
jscolor.install();
});
jsfiddle for working code
Could you please help to fix this issue?
Thanks

Right click JavaScript doesn't work on a table in PHP

Hy, I have a problem with my JavaScript that I use it for the content of a table. My function is for users when they right click on a table row appears a context menu where they can choose what they want to do. The problem is that right click doesn't work any more when I go to the next pages in the table (my page load with 10 records in the table).
My script:
<script type='text/javascript'>
$(window).load(function(){
(function ($, window) {
$.fn.contextMenu = function (settings) {
return this.each(function () {
// Open context menu
$(this).on("contextmenu", function (e) {
// return native menu if pressing control
if (e.ctrlKey) return;
//open menu
var $menu = $(settings.menuSelector)
.data("invokedOn", $(e.target))
.show()
.css({
position: "absolute",
left: getMenuPosition(e.clientX, 'width', 'scrollLeft'),
top: getMenuPosition(e.clientY, 'height', 'scrollTop')
})
.off('click')
.on('click', 'a', function (e) {
$menu.hide();
var $invokedOn = $menu.data("invokedOn");
var $selectedMenu = $(e.target);
var $selectedFileId = $menu.data("invokedOn").find('.datatable_fixed_column').attr('id');
settings.menuSelected.call(this, $invokedOn, $selectedMenu, $selectedFileId);
});
return false;
});
//make sure menu closes on any click
$('body').click(function () {
$(settings.menuSelector).hide();
});
});
function getMenuPosition(mouse, direction, scrollDir) {
var win = $(window)[direction](),
scroll = $(window)[scrollDir](),
menu = $(settings.menuSelector)[direction](),
position = mouse + scroll;
// opening menu would pass the side of the page
if (mouse + menu > win && menu < mouse)
position -= menu;
return position;
}
};
})(jQuery, window);
$("#datatable_fixed_column td").contextMenu({
menuSelector: "#contextMenu",
menuSelected: function (invokedOn, selectedMenu, id) {
switch(selectedMenu.text()){
case 'Modificare':{
var rand = invokedOn.parent().children();
var idpost = $(rand[0]).text();
window.location.href = "organigrama_add.php?control=update&id=" + idpost;
}
break;
case 'Stergere':{
var rand = invokedOn.parent().children();
var marca = $(rand[1]).text();
if (marca == '0')
{
var idpost = $(rand[0]).text();
var departament = $(rand[5]).text();
var subdepartament = $(rand[6]).text();
var schimb = $(rand[9]).text();
var functie = $(rand[10]).text();
var msg = "Sunteti sigur ca doriti sa stergeti aceasta inregistrare?" + "\nDepartament: " + departament + "\nSubdepartament: " + subdepartament + "\nSchimb: " + schimb + "\nFunctie: " + functie;
var confirmare = confirm(msg);
if (confirmare == true)
{
window.location.href = "organigrama.php?control=delete&id=" + idpost;
}
}
else
{
var msg = "Nu se poate sterge acest post. Doar posturile libere se pot sterge.";
alert(msg);
}
}
break;
case 'Renunta':{
return false;
}
break;
}
}
});
});
</script>
And context menu used for this:
<ul id="contextMenu" class="dropdown-menu" role="menu" style="display:none" >
<li><a tabindex="-1">Modificare</a></li>
<li><a tabindex="-1" href="#">Stergere</a></li>
<li class="divider"></li>
<li><a tabindex="-1" href="">Renunt</a></li>
</ul>
Edit: I forget to mention that the javascript is before the </body> end tag and context menu is after <body> start tag.
so basically the problem here is that the newly added rows in the table will not get the bindings from the initial load of the page. so the fix needed here is to bind the event to the main document by using this
$(document).on('contextmenu', target, function)
this will allow jquery to run the specific function to a targeted element on 'right click/contextmenu' event

Jquery with 2 clicks functions

I want to select or deselect a div with a click.
I want this :
click 1 = add color and select div
click 2 = if is the same id go pink, if different go white.
My problem is when I click on the first div (go red), then the second div (first go white and second too), then the third div, the third div go pink, or I want re run the script (for make the third div red like the first div).
My code:
$(document).ready(function () {
$i = 1;
$firstcase = "";
$(".blackcase").click(function firstclick(event) {
if ($i == 1)
{
$("#" + event.target.id).css("background-color", "red");
$firstvalue = $("\#" + event.target.id).html();
$firstcase = "\#" + event.target.id + "";
$i++;
}
else
{
return false;
}
$(".blackcase").one("click", function (event) {
$firstcase2 = "\#" + event.target.id + "";
if ($("#" + event.target.id).is($firstcase))
{
$("#" + event.target.id).css("background-color", "pink");
$i = 0;
$firstcase = "";
return;
}
else
{
$(".blackcase").css("background-color", "white");
$i = 1;
$firstcase = "";
return false;
}
});
return false;
});
});
JSFIDDLE: https://jsfiddle.net/12gwq95u/3/
You can massively simplify your logic if you have a single event handler and store the last clicked id in a variable outside of the click handler. Try this:
var lastClicked = '';
$(".blackcase").click(function(e) {
e.preventDefault();
$('.blackcase').removeClass('red pink');
$(this).addClass(lastClicked != this.id ? 'red' : 'pink');
lastClicked = this.id;
});
Example fiddle

Custom styled select box

am trying to use javascript for custom styled select boxes from www.gerrendesign.com/entry_images/selectboxdemo.zip
and as I have plenty entries inside one of select box I need to make but am stuck in creation of scrolling function.
As this select boxes are compatible with almost all older and new browsers. I need only suggestion or solution how to add scroll in this linked/attached files above - if select box is populated with plenty of entries (example cities, states, or exchange rates...)
Am stuck here...
Thanks for your cooperation
Ivan
THIS IS CODE:
$(document).ready(function(){
// first locate all of the select tags on the page and hide them
$("select.changeMe").css('display','none');
//now, for each select box, run this function
$("select.changeMe").each(function(){
var curSel = $(this);
// get the CSS width from the original select box
var gddWidth = $(curSel).css('width');
var gddWidthL = gddWidth.slice(0,-2);
var gddWidth2 = gddWidthL - 28;
var gddWidth3 = gddWidthL - 16;
// build the new div structure
var gddTop = '<div style="width:' + gddWidthL + 'px" class="selectME" tabindex="0"><div class="cornerstop"><div><div></div></div></div><div class="middle"><div><div><div>';
//get the default selected option
var whatSelected = $(curSel).children('option:selected').text();
//write the default
var gddFirst = '<div class="first"><span class="selectME gselected" style="width:'+ gddWidth2 + 'px;">'+ whatSelected +'</span><span id="arrowImg"></span><div class="clears"></div></div><ul class="selectME">';
// create a new array of div options from the original's options
var addItems = new Array();
$(curSel).children('option').each( function() {
var text = $(this).text();
var selVal = $(this).attr('value');
var before = '<li style="width:' + gddWidthL + 'px;"><a href="#" rel="' + selVal + '" tabindex="0" style="width:' + gddWidth3 + 'px;">';
var after = '</a></li>';
addItems.push(before + text + after);
});
//hide the default from the list of options
var removeFirst = addItems.shift();
// create the end of the div selectbox and close everything off
var gddBottom ='</ul></div></div></div></div><div class="cornersbottom"><div><div></div></div></div></div>'
//write everything after each selectbox
var GDD = gddTop + gddFirst + addItems.join('') + gddBottom;
$(curSel).after(GDD);
//this var selects the div select box directly after each of the origials
var nGDD = $(curSel).next('div.selectME');
$(nGDD).find('li:first').addClass("first");
$(nGDD).find('li:last').addClass('last');
//handle the on click functions - push results back to old text box
$(nGDD).click( function(e) {
var myTarA = $(e.target).attr('rel');
var myTarT = $(e.target).text();
var myTar = $(e.target);
//if closed, then open
if( $(nGDD).find('li').css('display') == 'none')
{
//this next line closes any other selectboxes that might be open
$('div.selectME').find('li').css('display','none');
$(nGDD).find('li').css('display','block');
//if user clicks off of the div select box, then shut the whole thing down
$(document.window || 'body').click( function(f) {
var myTar2 = $(f.target);
if (myTar2 !== nGDD) {$(nGDD).find('li').css('display','none');}
});
return false;
}
else
{
if (myTarA == null){
$(nGDD).find('li').css('display','none');
return false;
}
else {
//set the value of the old select box
$(curSel).val(myTarA);
//set the text of the new one
$(nGDD).find('span.gselected').text(myTarT);
$(nGDD).find('li').css('display','none');
return false;
}
}
//handle the tab index functions
}).focus( function(e) {
$(nGDD).find('li:first').addClass('currentDD');
$(nGDD).find('li:last').addClass('lastDD');
function checkKey(e){
//on keypress handle functions
function moveDown() {
var current = $(nGDD).find('.currentDD:first');
var next = $(nGDD).find('.currentDD').next();
if ($(current).is('.lastDD')){
return false;
} else {
$(next).addClass('currentDD');
$(current).removeClass('currentDD');
}
}
function moveUp() {
var current = $(nGDD).find('.currentDD:first');
var prev = $(nGDD).find('.currentDD').prev();
if ($(current).is('.first')){
return false;
} else {
$(prev).addClass('currentDD');
$(current).removeClass('currentDD');
}
}
var curText = $(nGDD).find('.currentDD:first').text();
var curVal = $(nGDD).find('.currentDD:first a').attr('rel');
switch (e.keyCode) {
case 40:
$(curSel).val(curVal);
$(nGDD).find('span.gselected').text(curText);
moveDown();
return false;
break;
case 38:
$(curSel).val(curVal);
$(nGDD).find('span.gselected').text(curText);
moveUp();
return false;
break;
case 13:
$(nGDD).find('li').css('display','none');
}
}
$(document).keydown(checkKey);
}).blur( function() {
$(document).unbind('keydown');
});
});
});
You could render the list inside a div, that has either a fixed height or a max-height (depending on your cross-browser requirements). Presuming the default scroll bar is ok...
If structure is something in the direction of
<div class="select_data_container">
<ul class="select_rows">
<li>row1</li>
<li>row2</li>
</ul>
</div>
CSS-example could be
.select_data_container {overflow-y: auto; height: 200px;}
.select_rows {display:block;}

Categories