redips.drag get row id when row is dropped and send to server - javascript

I am building a django site and have implemented the redips.drag library in one of my pages to allow dragging of table rows. I want a very simple functionality in my code- add a listener, so when the row is dropped, it send the row data to the server. jQuery-speaking, something like this:
$(function() {
$(someDomElement).on('DropEvent', function() {
// send data to server
};
});
The problem though, is that redips.drag is not a jQuery plugin but a javascript one, so my knowledge is a little (more than a little) lacking. I can probably find some other library, but it's performing really well and I prefer understanding how to work with it than look for a different one.
I can probably handle the "sending the data to the server" part by myself, what I can't understand at all is how to "catch" the drop event, what part of the dom do I listen to? I tried adding monitorEvents to different selectors but failed completely.
I also tried to manipulate the script.js file (the one that initializes the row handling), but also failed. here's the one I'm using (example 20 in the redips package):
"use strict";
// define redips object container
var redips = {};
redips.init = function () {
// reference to the REDIPS.drag library and message line
var rd = REDIPS.drag,
msg = document.getElementById('msg');
// initialization
rd.init();
//
// ... more irrelevent code ...
//
// row event handlers
//
// row clicked (display message and set hover color for "row" mode)
rd.event.rowClicked = function () {
msg.innerHTML = 'Clicked';
};
// row row_dropped
rd.event.rowDropped = function () {
msg.innerHTML = 'Dropped';
};
// and so on...
};
// function sets drop_option parameter defined at the top
redips.setRowMode = function (radioButton) {
REDIPS.drag.rowDropMode = radioButton.value;
};
// add onload event listener
if (window.addEventListener) {
window.addEventListener('load', redips.init, false);
}
else if (window.attachEvent) {
window.attachEvent('onload', redips.init);
}
Now I tried adding a console.log('hello') to the rd.event.rowDropped function (right above the msg.innerHTML line), but that doesn't work, I drop the row and nothing shows in the log. Doing a console.log outside the init function works so I know the script can pass stuff to the console.
Please, can anyone help me? I'm at a complete loss...

I know this may be a little lateto answer your question but I found the answer. You need to use the event dropped and the attribute rd.obj (REDIPS.drag.obj) to get the id use it with simple javascript like getAttribute('id')
redips.init = function () {
// reference to the REDIPS.drag library and message line
var rd = REDIPS.drag,
msg = document.getElementById('msg');
// initialization
rd.init();
// row clicked (display message and set hover color for "row" mode)
rd.event.clicked = function () {
msg.innerHTML = 'Clicked' + rd.obj.getAttribute('id');
};
// row row_dropped
rd.event.dropped = function () {
msg.innerHTML = 'Dropped' + rd.obj.getAttribute('id');
};
};

Related

Move color of an HTML element to another page

Good evening,
i was working on a part of what i hope will be my future website and i wanted to add a "photograpy" section to it, and here comes the problem.
since the title in the main page constatly changes color, i'd like to grab its current color to transfer it to the title of the other page to play an animation later on.
the problem is that when i press the related button, i am taken to the photograpy page, but the title remains black.
i've tried seraching for help on google but i haven't been able to find much.
here is the JS
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", function() {
loaded();
});
} else if (document.attachEvent) {
document.attachEvent("onreadystatechange", function() {
loaded();
});
}
function loaded() {
document.getElementById("PHtitle").style.color === titlecolor;
}
function script() {
const titlecolor = document.getElementById("title").style.color;
};
document.getElementById('photograpy').onclick = function () {
script();
};
The snippets don't allow for localStorage, so here is just the javascript.
First, I let the variables outside of a function. The titleColor function checks to see if titleColor was saved in localStorage, if not the default color is black.
Then I set the color of the phtitle to the contents of titleColor variable.
In the script function, I set the localStorage variable to the getComputedStyle color of the title.
Then last I use an event listener on the button to run the script for saving the color.
LocalStorage is a way to store data in the user's browser until they close their browser/clear their data etc.. Which will allow it to be usable on different pages then where it was saved.
let titleColor = localStorage.getItem("titleColor") || "#000000";
let PHtitle = document.querySelector("#PHtitle");
let title = document.querySelector("#title");
let btn = document.querySelector("#photography");
if(PHtitle){
PHtitle.style.color = titleColor;
}
function script() {
localStorage.setItem("titleColor", getComputedStyle(title).color)
}
if(btn && title){
btn.addEventListener("click", function() {
script();
})
}

i have problem in ajax Post not display data

i have table with search fields seprated to
1- table header contain "search fields - table headers"
2- table body => come from ajax post method
3- pagination => come from ajax post method after data excuted "i used setTimeout to delay this function"
the data display automaticly in the table body by ajax post & if the user use search fields also the data filterd by search words and pagingation also display basd on data
i have 2 cases
1- in the main page the table loaded with the page and evry thing working fine i used the follwing function:
follwing function responsible for data
jsQueryDataLive(defaultPageNo);
function jsQueryDataLive(defaultPageNo){
var objData = {
action : dataTableName +'/QueryData',
ajaxClass : actionSplit0,
ajaxPage : defaultPageNo,
};
$('#form-query-main').find(":input").each(function(){
objData[this.name] = $(this).val();
});
// console.log(objData);
// NOTE: the below line is Responsible for determining the location we need to view data on
var locationID = '#main-table-tbody';
ajaxPost(objData, locationID);
}
the following function for pagination
jsPaginationLive(defaultPageNo);
function jsPaginationLive(defaultPageNo){
setTimeout(function () {
var objData = {
action : dataTableName +'/Pagination',
ajaxClass : actionSplit0,
ajaxPage : defaultPageNo,
};
// document.getElementById("jsData").innerHTML =JSON.stringify(objData);
// NOTE: the below line is Responsible for determining the location we need to view data on
var locationID = '#pagination';
ajaxPost(objData, locationID);
}, 100);
}
i used the following function for filter
$('.searchField').keyup(function() {
jsPageNo(defaultPageNo);
} );
function jsPageNo(defaultPageNo) {
jsQueryDataLive(defaultPageNo);
jsPaginationLive(defaultPageNo);
}
2- the second case is when i want to display the obove bage in the modal
as you see in the page the table and data display correctly
i used this function to define table and load the main bag :
var dataTableName;
jsDataTableName();
function jsDataTableName(tableName) {
if (tableName === undefined) {
dataTableName = actionSplit0;
// console.log(dataTableName);
}
else {
dataTableName = tableName;
console.log(dataTableName);
// NOTE: load External Class Query page
jsLoadExternalClass();
}
}
function jsLoadExternalClass(){
var objData = {
action : dataTableName +'/Query',
ajaxClass : actionSplit0,
ajaxPage : defaultPageNo,
};
// document.getElementById("jsData").innerHTML =JSON.stringify(objData);
// jsPaginationLive(defaultPageNo);
// NOTE: the below line is Responsible for determining the location we need to view data on
var locationID = '#externalClass1';
ajaxPost(objData, locationID);
jsPageNo(defaultPageNo);
}
the problem with me in filtered not working when i type imediatly but it work after i close the modal and re open it again
enter image description here
also if there is a better solution to start function jsPaginationLive after jsQueryDataLive finished instead of setTimeout please let me know
If you set the timer on setTimeout from 100 ms to 2,000, does it still have the issue? One of the problems I've run into when using timeouts to handle situations like these is that any variance in the loading times of the site (which can always vary for any number of reasons) can cause your timeout to fail to achieve your goal.
So instead I'd suggest this: either add a variable which is set by the data function upon completion or you could use a value in the data function which must not be undefined before proceeding, then have the pagination function in a setInterval, like this:
var interval;
interval = setInterval(function(){
if (dataHasLoaded){ // This will be whatever the you decide to name the variable
jsPaginationLive(defaultPageNo);
clearInterval(interval);
}
},500);
This will ensure that the pagination function will never attempt to load before the data has been fully loaded.
EDIT: Alternatively, you can place "jsPaginationLive(defaultPageNo);" somewhere at the end of "jsQueryDataLive(defaultPageNo);" so it won't attempt pagination until the data function has completed.
Answer to 2nd question:
If you want to only run an interval while a user is typing, you can do something like this:
var interval;
window.onkeydown = function(){
clearInterval(interval);
interval = setInterval(function(){
if (dataHasLoaded){
jsPaginationLive(defaultPageNo);
clearInterval(interval);
}
},500);
}
var keyTimeout;
window.onkeyup = function(){
clearTimeout(keyTimeout);
keyTimeout = setTimeout(function(){
clearInterval(interval);
}, 5000); // The interval will be cleared 5 seconds after the last keypress. Change as needed.
}
I feel like there's a cleaner way to do this, though. Why do you want the interval to only be active during typing?

window. onload=function() just works without cached DOM

The product image is displayed as inline SVG and receives a new color for specific paths, depending on the dropdown selection.
"use strict";
window.onload=function(){
var dropdownColor = document.getElementById('Color');
// When a new <option> is selected
dropdownColor.addEventListener('change', function() {
var selectPathSvg = document.getElementById('pathNumber');
//get value text
var colorValue= selectElemFerse.options[selectElemFerse.selectedIndex].text;
//Clear all Classes from SVGPath
selectPathSvg .classList = '';
// Add that class to the <p>
selectPathSvg.classList.add(colorValue);
})
}
But this Javascript code works only, if the page was read in the DOM for the first time. If you reload this page with F5, this will not lead to any errors in the console, but not to the desired result.
EDIT: Nothing here worked for me. But I noticed that if I delete the `woocommerce_recently_viewed``cookie, that the systems works fine. But how to fix such a thing?
It's generally bad practice to use onload = ... You should instead try using addEventListner("load", ...)
The reason your script does not run, is because it gets compiled after the page has been fully loaded, so you should also check if the load event has already been fired.
"use strict";
if(document.readyState === "complete") onLoad();
else addEventListener("load", onLoad);
function onLoad(){
console.log("Doing on load stuff here...");
}
Try this instead and see if it works:
window.addEventListener('DOMContentLoaded', (event) => {
var dropdownColor = document.getElementById('Color');
// When a new <option> is selected
dropdownColor.addEventListener('change', function() {
var selectPathSvg = document.getElementById('pathNumber');
//get value text
var colorValue= selectElemFerse.options[selectElemFerse.selectedIndex].text;
//Clear all Classes from SVGPath
selectPathSvg .classList = '';
// Add that class to the <p>
selectPathSvg.classList.add(colorValue);
})
});

DataTables inform load time while loading AJAX data

I have some tables that start empty and DataTables requests WebServer for the data.
It's ok to take some minutes to load it. DataTables shows default Loading message. But I'd like to add a counter informing how long the loading is running, instead of a simple Loading text or some wacky animation.
I can't find a way to do it on its documentation. Is it possible?
Update: MonkeyZeus's answer worked perfectly. Here's my final code:
// ...
,dataTablesLoading: function(e, settings, processing ){
setTimeout(function(){
var targetJs = e.target;
var target = $(targetJs);
var timerContainer = target.find('.dataTables_empty');
//tlog(targetJs,'targetJs');
//tlog(target,'target');
//tlog(timerContainer,'timerContainer');
if(processing){
var timer = 0;
var timerHandler = setInterval(function(){
timer++;
var hours = Math.floor(timer/3600);
var minutes = Math.floor((timer-(hours*60))/60);
var secs = timer-(hours*3600)-(minutes*60);
var timerText = hours+':'+minutes.lpad("0",2)+':'+secs.lpad("0",2);
tlog(timerText,'timerText');
//tlog(timerContainer,'timerContainer');
timerContainer.text("Loading... "+timerText);
},1000);
targetJs.setAttribute("data-loading-timer",timerHandler);
tlog(timerHandler,'timerHandler processing');
}else{
var timerHandler = parseInt(targetJs.getAttribute("data-loading-timer"));
tlog(timerHandler,'timerHandler not processing');
if(timerHandler>0)
clearInterval(timerHandler);
}
},1000);
}
// ...
$('#...')
.on( 'processing.dt', Framework.utils.dataTablesLoading )
.DataTable({...})
First, you will need to enable processing when invoking the datatable:
$('#example').dataTable( {
"processing": true
} );
Next, you will need to declare what happens instead of the default Loading message using the dt namespace's processing event listener:
// This event will fire twice so pay attention to the processing parameter
$('#example').on( 'processing.dt', function ( e, settings, processing ) {
if( processing === true ) {
alert('Hey, we are processing!');
// some custom code which targets #processingIndicator and applies some timer plug-in or whatever; you figure it out.
}
else {
alert('Hey, we are done processing!');
// some custom code which targets #processingIndicator and hides it; you figure it out.
}
} )
.dataTable();
Additionally, long load times have a UX aspect to consider as well so definitely check out https://ux.stackexchange.com/a/80858/45170 if you want to make a nicer experience.

Commit settings instantly Windows 8 app

I'm trying to make a test app for Windows 8 that has two input boxes and one button (lets call it "Calculate" button). When the user presses the button he gets a result. He can enter his details in either metric or imperial units by choosing which units he wants to use in the settings flyout. Now what I'm trying to do is to commit the changes instantly. When the user selects for example the imperial units the input boxes and the result automatically change to imperial. Right now when I change the units from metric to imperial I must press the "Calculate" button again to see the results in imperial.
How can I do that?
Below is some of my code.
In the default .js file I created a button handler:
var test = document.getElementById("button");
test.addEventListener("click", doDemo, false);
In the main .js file where all the calculations are done it looks like this:
function doDemo(eventInfo) {
var applicationData = Windows.Storage.ApplicationData.current;
var roamingSettings = applicationData.roamingSettings;
if (roamingSettings.values["cmorft"] == 'imperial') {
var greetingString3 = "Imperial";
document.getElementById("units").innerText = greetingString3;
} else {
var greetingString4 = "metric";
document.getElementById("units").innerText = greetingString4;
}
I used the following to save the user's choice:
var applicationData = Windows.Storage.ApplicationData.current;
var roamingSettings = applicationData.roamingSettings;
WinJS.UI.Pages.define("/html/settings.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
var imperialRadio = document.getElementById("imperial"),
metricRadio = document.getElementById("metric");
// Set settings to existing values
if (roamingSettings.values.size > 0) {
if (roamingSettings.values["cmorft"]) {
setMIValue();
}
}
// Wire up on change events for settings controls
imperialRadio.onchange = function () {
roamingSettings.values["cmorft"] = getMIValue();
};
metricRadio.onchange = function () {
roamingSettings.values["cmorft"] = getMIValue();
};
},
unload: function () {
// Respond to navigations away from this page.
},
updateLayout: function (element, viewState, lastViewState) {
// Respond to changes in viewState.
}
If I understand you correctly, you simply need to set the innerText properties of your HTML elements when you change the units, not just when you click the button. In your demo it can be as simple as calling doDemo from within the onchange handlers for your radiobuttons, as that will read the updated setting and set the text.

Categories

Resources