JavaScript behaving weirdly, opening an drop/drag item only 'alert' is put - javascript

I have Drag/Drop functionality in my page embedded using YAHOO.js which is initalized at load of the page. When 'alert' is put in the init function, the Drag/Drop is working otherwise
it is not. Using Firebug I had debugged the code and seen when init function is called but not looping through the function when no alert is put.
This function should work when ALT key is pressed. I am using velocity template engine over JavaScript.
Sample code:
<script type="text/javascript" language="JavaScript">
var myLogger;
var dd1, ddTrashCan; // draggable div objs
#if ($displayOptions.isDoDragDropJavaScript())
YAHOO.util.Event.addListener(window, "load", DD_TestInit);
#end
function display(data) {
var output = "<div>" + data.text + "</div>";
element.innerHTML=output;
}
function DD_TestInit() {
#if ($showLoggerDiv)
initLogger();
#end
//display("date");
initDragObjects();
}
function logMsg(strMsg) {
if (myLogger)
myLogger.debug(strMsg);
}
function initDragObjects() {
//alert('---');
if (dd1) dd1.unreg();
if (ddTrashCan) ddTrashCan.unreg();
YAHOO.util.DDM.mode = YAHOO.util.DDM.POINT;
YAHOO.util.DDM.clickTimeThresh = 10;
## init constant drag objects, draggable div and droppable trash, resp.
dd1 = new lineSched_Draggable("dragDiv1");
ddTrashCan = new lineSched_Droppable("TrashCan");
}
What I had found is whenever I put an alert or call any window.open() this works fine.
Any clue whats happening here.

There is timer event which is delaying the process.My feeling is that this is a timing issue. The page is not fully in place when on load. The alert slows the process down, essentially the page is in place by the time the user clicks Ok on the alert. Clearly, we can’t deploy the app with an alert. But, we can look into different places to put the initialization. We can try to place it the same place I added the timing, when the page receives the last table. The page should be fully formed at this point and the function should work properly.

Related

JavaScript only being called once in Squarespace

I have some custom JavaScript on my SquareSpace site that manipulates Product titles beyond what you can do with SquareSpace's default style editor. It works when initially loading the page (https://www.manilva.co/catalogue-accessories/) but if you click on any of the categories on the left, the styling resets to the default.
I'm assuming the JavaScript is being overwritten by the SquareSpace style, but I can't figure out why. Perhaps I'm calling the function in the wrong place?
Any suggestions would be helpful.
Thanks!
Current code:
document.querySelectorAll(".ProductList-filter-list-item-link".forEach(i=>i.addEventListener("click", function()
{
var prodList = document.querySelectorAll("h1.ProductList-title");
for (i = 0, len = prodList.length; i < len; i++)
{
var text = prodList[i].innerText;
var index = text.indexOf('-');
var lower = text.substring(0, index);
var higher = text.substring(index + 2);
prodList[i].innerHTML = lower.bold() + "<br>" + higher;
});
The source of your problem is that your template has AJAX loading enabled. There are currently a couple generally-accepted ways to deal with this as a Squarespace developer:
Disable AJAX loading
Write your javascript functions in a
manner that will run on initial site load and whenever an "AJAX load" takes place.
Option 1 - Disable AJAX:
In the Home Menu, click Design, and then click Site Styles.
Scroll down to Site: Loading.
Uncheck Enable Ajax Loading.
Option 2 - Account for AJAX in Your JS
There are a number of ways that developers approach this, including the following, added via sitewide code injection:
<script>
window.Squarespace.onInitialize(Y, function() {
// do stuff
});
</script>
or
<script>
(function() {
// Establish a function that does stuff.
var myFunction = function() {
// Do stuff here.
};
// Initialize the fn on site load.
myFunction();
// myFunction2(); , etc...
// Reinit. the fn on each new AJAX-loaded page.
window.addEventListener("mercury:load", myFunction);
})();
</script>
or
<script>
(function() {
// Establish a function that does stuff.
var myFunction = function() {
// Do stuff here.
};
// Initialize the fn on site load.
myFunction();
// Reinit. the fn on each new AJAX-loaded page.
new MutationObserver(function() {
myFunction();
// myFunction2(); , etc...
}).observe(document.body, {attributes:true, attributeFilter:["id"]});
})();
</script>
Each of those works for most of the latest (at time of writing) templates most of the time. Each of those have their advantages and disadvantages, and contexts where they do not work as one might expect (for example, on the /cart/ page or other "system" pages). By adding your code within the context of one of the methods above, and ensuring that the code is of course working in the desired contexts and without its own bugs/issues, you will have your code run on initial site load and on each AJAX page load (with some exceptions, depending on the method you use).
Your problem is the page does not reload when clicking a button on the left, just some elements are removed, added and replaced. The changed elements will not be restyled. You will need to re-run your JavaScript after one of those buttons is clicked. Perhaps something like this:
document.querySelectorAll(
".ProductList-filter-list-item"
).forEach(
i=>i.addEventListener(
"click", ()=>console.log("hello")
)
)
where you replace console.log("hello") with whatever resets your formatting.

document.querySelector(".class h1")

I'm working on my schools webpage, and i'm trying to select all header elements inside a div with a class called "text" using the querySelector(String) function - and then changing the headers background, border, and text colour, but the following code doesn't seem to work
var test = "content.html #test"
$(document).ready(function()
{
$.ajax(
{
success : function(data)
{
$("#content").load(test); //this works - loads <div id="test"> and all elements within it from content.html
document.querySelector(".content").style.backgroundColor = "#CCFFCC"; //this works - exists inside main html file ( $(document) )
document.querySelector(".text h1").style.backgroundColor = "#CCFFCC"; //this doesn't work - still loading default colour from css
document.querySelector(".text h1").style.color = "#003300"; //this doesn't work - still loading default colour from css
//Appropriate close tags follow...
Would you guys know what i'm doing wrong? Am I referencing my elements in the wrong way? or does it have something to do with the fact that i'm trying to dynamically load this content from a separate file? Or something else entirely?
As Klaster_1 intimated, you need to utilize load's callback functionality.
$('#content').load(test, function() {
document.querySelector(".content").style.backgroundColor = "#CCFFCC";
document.querySelector(".text h1").style.backgroundColor = "#CCFFCC";
document.querySelector(".text h1").style.color = "#003300";
});
What Klaster_1 means when he says it's an "async" operation is that it runs out of sync of the rendering of the DOM. In other words, that code styling the content will be run before the browser's run loop has a chance to actually put the content on the page.

Bootstrap modal only shows after function completes, but not when I call it

I'm creating a HTML5 tool for something at my work.
My goal is:
Click the Go! button. Show the modal. Start the process of getting the lat long for all entered locations by starting the each loop and get the locations lat/lon via the ajax requests and closing the modal when these are all done.
The modal can be shown by using the button TEST and it can also be shows after the function finishes but not when it starts.
$(document).ready(function () {
$('#pleaseWaitDialog').click(function () {
$('#pleaseWaitDialog').modal('hide');
});
$('#csvImportBtn').click(function () {
$('#pleaseWaitDialog').modal('show');
var csvText = $('#csvUpload').val();
var data = csvUpload(csvText);
$('#status').html('Getting lat long for: ' + data.length + 'devices...');
getLatLon(data);
});
});
Here is the fiddle of the complete page, it doesn't seem to work for me from jsfiddle, but I can run it in a normal HTML page without errors.
I've tested this in Chrome 'Version 38.0.2125.111 m'.
Can anyone advise how I'll be able to show it on the start of the process (after clicking Go!)? Because I'm pretty lost right now.
Edit:
Here is the testdata to be pasted in the textarea:
device_id,address,city
118001,Wipmolenweg 13,Almere
118002,Wipmolenweg 14,Almere
118003,Wipmolenweg 15,Almere
118004,Wipmolenweg 16,Almere
118005,Wipmolenweg 17,Almere
118006,Wipmolenweg 18,Almere
118007,Wipmolenweg 19,Almere
118008,Wipmolenweg 20,Almere
118009,Wipmolenweg 21,Almere
118010,Wipmolenweg 22,Almere
Edit: Still stuck.. Can anybody help? Also changed the title for a better description.

addEventListener to div element

I am trying to fire a script when the contents of a div are altered, specifically when a div receives the next set of results from a js loaded paginator.
I have this:
<script script type="text/javascript" language="javascript">
document.addEventListener("DOMCharacterDataModified", ssdOnloadEvents, false);
function ssdOnloadEvents (evt) {
var jsInitChecktimer = setInterval (checkForJS_Finish, 111);
function checkForJS_Finish () {
if ( document.querySelector ("#tester")
) {
clearInterval (jsInitChecktimer);
//do the actual work
var reqs = document.getElementById('requests');
var reqVal = reqs.get('value');
var buttons = $$('.clicker');
Array.each(buttons, function(va, index){
alert(va.get('value'));
});
}
}
}
</script>
This works well when the doc loads (as the results take a few seconds to arrive) but I need to narrow this down to the actual div contents, so other changes on the page do not fire the events.
I have tried:
var textNode = document.getElementById("sitepage_content_content");
textNode.addEventListener("DOMCharacterDataModified", function(evt) {
alert("Text changed");
}, false);
But the above does not return anything.
Can what I am trying to do be done in this way? If yes where am I going wrong?
Using Social Engine (Zend) framework with MooTools.
I did this in the end with a little cheat :-(
There is a google map loading on the page that sets markers to match the location of the results. So I added my events to the end this code namely: function setMarker() {}.
I will not mark this as the correct answer as it is not really an answer to my question, but rather a solution to my problem, which is localised to the Social engine framework.
I will add a Social engine tag to my original question in the hope it may help someone else in the future.
Thanks guys.

sending div to another page

i would like to send a div to another page actually im using javascript it work but i dont think its effecient cause it just show it it dont really send it, is there another way with ajax or jquery //my script send div:envoi to contenu.php under div:recu
function popWindow()
{
var pop = window.open('contenu.php'); self.focus();
if(pop.focus){ pop.focus(); }
}
function showIt() {
var cont = self.opener.document.getElementById('Envoi').innerHTML;
document.getElementById('recu').innerHTML = cont;
}
As far as I'm aware, that should work, assuming the showIt function is called within the popup window, within the onload event of the page body (or at some point after the 'recu' element have been drawn).

Categories