Return URL with JavaScript that Prevents Loading of Cached Pages

HTML and JS logos

If you want to force a page to reload from the server rather than getting a cached copy, one way to do it is to append a query string to the URL.

If you want your web application to generate URLs that have this functionality, the code below can be implemented using JavaScript. Inside a file called BrowserUtility.js, insert this code.

function BrowserUtility()
{
	this.addNoCacheTimestamp =
		function(sUrl)
		{
			var ts = 'noCacheTS=' + (new Date()).getTime();
			sUrl = sUrl.trim();
			var nQIndex = sUrl.indexOf('?');
			sUrl+=(nQIndex==-1)?'?':(nQIndex===sUrl.length-1)?'':'&';
			return sUrl+=ts;
		};
};

var browserUtility = new BrowserUtility();

Once this is loaded, the function can be called like this, where the variable sUrl stores a URL:

sUrl = browserUtility.addNoCacheTimestamp(sUrl);

If the variable sUrl initially contained “http://example.com”, the returned string would be something like “http://example.com?noCacheTS=201808081203”.

Another option, if you did not want to use the current time as the query string value, would be to use a random number function instead.

(This is a snippet of code that I didn’t write – it was authored by my friend and colleague Jeff Konicky.)

Stripping HTML Tags from Textboxes Using JavaScript

HTML tags

One of the applications I support routinely has a problem where users cut and paste text that contains HTML tags from other sources into the text boxes on entry forms in my application. Most of the time, this does not cause a problem. However, if the users do not capture all of the text, they may unwittingly not grab the closing tags. When that happens, all sorts of fun things can happen to the main page on the app, which shows recent entries.

I decided I’d like to remove all HTML, except I’d like to retain line breaks. Based partially on a solution I found on Stack Overflow, I made this function.

this.fixHtml =
	function(strHtml)
	{
		var div = document.createElement('div');
		strHtml = strHtml.replace(/<br>/gi,'\n');
		strHtml = strHtml.replace(/<br \/>/gi,'\n');
		div.innerHTML = strHtml;
		strHtml = div.innerText || div.textContext;
		strHtml = strHtml.replace(/\n/gi,'<br />');
		div.innerHTML = strHtml;			
		return div.innerHTML;
	};

I call the fixHtml function whenever an input tag is of type text, or if a div element is of the class “mimicTextArea” (it looks like a text box):

if(oForm!=null)
{
	var oInputs = oForm.getElementsByTagName("input");
	for(var x=0;x<oInputs.length;x++)
	{
		if(oInputs[x].type=="text" && oInputs[x].value.length > 0)
		{
			oInputs[x].value = self.fixHtml(oInputs[x].value);
		}
	}
	
	var oDivs = oForm.getElementsByTagName("div");
	for(var x=0;x<oDivs.length;x++)
	{
		if(oDivs[x].className == "mimicTextArea" && oDivs[x].innerHTML.length > 0)
		{
			oDivs[x].innerHTML = self.fixHtml(oDivs[x].innerHTML);
		}
	}
	
}

This seems to serve my purpose well. Should I wish to retain other specific HTML tags, a similar technique may be used as above if they are self-closing tags such as the line break tag. Tags that require an opening and a closing tag would require further development.

Using CSS to Create Resizable Columns in WordPress with Thesis Theme…Part Deux!

CSS variable declaration and use

About three years ago, I wrote a post about dynamically resizing the content column in WordPress.org when using the Thesis theme.

The method described in that post worked fine until Thesis 2.4 was released last August. At that time, I noticed that my columns were no longer the full width of the window, and did not change size as I expanded or shrank the window. I sent an email to Thesis support and was told that a Box called Fix CSS would likely fix my problem. I installed it, but to no avail. Upgrading to Thesis 2.6 last month also had no effect.

Last week I decided to send another email and got a little more information. The creator of Thesis responded. Part of the message is below.

“Thesis 2.6 has ‘clarified’ the way you can use variables. Here’s how it works…

DO NOT:
Modify the Skin CSS, Editor CSS, or CSS Variables that come with your Thesis Skin. Whenever a Skin is updated, these three items will be overwritten, and you will lose any changes you’ve made to them.

DO:
Isolate ALL your CSS changes to the Custom CSS interface. Your modifications will be safe here during future Skin updates.
Create inline variables inside your Custom CSS interface, as seen in the image below:

picture of Custom CSS screen in Thesis

You can REFERENCE existing CSS Variables in your Custom CSS code, and you can also create and reference your own variables (like those shown in the image above) here as well.”

Now I had to implement the same steps as before in the previous post, but using this new method.

While the changes causing the builtin variables to revert to their original values may have been implemented in 2.6, my code had quit working at 2.4. So there’s a mystery! First, I removed the custom code and deleted the new variables from the Skin CSS so that it would be as it would directly downloaded the Thesis website.

Then, I basically set up new variables in the Custom CSS using the syntax shown in the screenshot above. I hit a snag here, however. For whatever reason, the CSS engine no longer supported the CSS calc() function! Also, I discovered that some of the CSS class names I originally used seemed not to affect the style of the column any longer.

The code below, which I appended to the bottom of my Custom CSS, does several things. First, it declares variables for the Custom CSS page in Thesis. Secondly, it implements those custom variables on the appropriate CSS classes and overrides the Skin CSS in all places where the variables $w_total and $w_content were used. Lastly, it declares a CSS variable to store the value in the builtin $w_sidebar Thesis variable. This will be useful in the next step, in which I will use a workaround for the lack of a working CSS calc() function.

$w_total_new = 80%;
$w_total_min = 897px;
$w_content_min = 585px;

.container, .columns > .content{
	max-width: $w_total_new;
	width: auto;	
}

.landing .container{	
	min-width: $w_content_min;
}

.full_width{
	min-width: $w_total_new;
}

.columns > .sidebar {	
	max-width: $w_sidebar;
}

:root{
	--sidebar: $w_sidebar;	
}

Since the modified $w_content variable in the original post used calc(), we’ll have to use the magic of JavaScript and jQuery to change the CSS after the page is loaded.

First, I grab the CSS variable called “–sidebar” by combining the window.getComputedStyle() method and the CSSStyleDeclaration.getPropertyValue() method interface.

I then trim the returned value to eliminate whitespace, and concatenate the string “-=” with the sidebar value which, incidentally, is currently 312px by default.

Then, I set the CSS to 100% for the classes listed. I then subtract (hence the “-=”) the sidebar width.

This:

$w_content = calc(100% - $w_sidebar);

Becomes this:

var sidebar = '-=' + window.getComputedStyle(document.body).getPropertyValue('--sidebar').trim();
if (sidebar==='-=') {
	sidebar = '-=' + window.getComputedStyle($('.sidebar')[0]).getPropertyValue('max-width').trim();
}
$('.landing .container, .columns > .content').css('width', '80%').css('width', sidebar);	 

Lastly, I wrapped it in a jQuery function that runs only after the window (including the CSS files) is fully rendered. The completed code below may be put in a Custom HTML widget in WordPress.

<script>
(function($) {
$(window).load(function() {	
	var sidebar = '-=' + window.getComputedStyle(document.body).getPropertyValue('--sidebar').trim();
	if (sidebar==='-=') {
		sidebar = '-=' + window.getComputedStyle($('.sidebar')[0]).getPropertyValue('max-width').trim();
	}
	$('.landing .container, .columns > .content').css('width', '100%').css('width', sidebar);	 
	$('img').each(function(){ 
		var image = $(this); 
		if(image.context.naturalWidth === 0 || image.readyState === 'uninitialized'){  
		$(image).unbind('error').hide();
      }	
	});	
});
})(jQuery);
</script>

Voila! The content column is once again resizable!

Nota bene: This has only been tested on the Social Triggers skin for Thesis. Other skins may use different CSS classes, so YMMV.

When JavaScript’s deleteRow() Method Doesn’t Work

A section of JavaScript code that uses the method deleteRow() was giving me a headache in IE 11. I did not encounter this when using Chrome.

In the code segment below, the variable “oHtmlTable” is assigned to an HTML table that already exists on a webpage.

//delete prior entries
while(oHtmlTable.rows.length > 1)					
{
	oHtmlTable.deleteRow(-1);
}

For no apparent reason, during the execution of the while loop, the deleteRow() method would quit working, but did not cause an exception to be thrown. Since the condition on the while loop would never be met if the rows in the table were no longer being deleted, this became an infinite loop.

IE gave no obvious indication as to what the problem was, just the standard “[domain name] is not responding” message at the bottom of the screen.

not responding

The code inside the while loop deletes the last row in the table. Whatever was inside the last row was keeping IE from successfully deleting it. First, I tried emptying the innerHTML contents of the last row to see if that would allow the deletion to continue. This had no effect. However, deleting the outerHTML contents of the row did the trick.

I created a variable in which to store the number of rows in the table, then an if statement to determine whether the row count changed after the deleteRow method was executed. If it was not, then on the next pass through the loop, the row would be deleted.

//delete prior entries
var nLength = 0;
while(oHtmlTable.rows.length > 1)					
{
	nLength = oHtmlTable.rows.length;
	oHtmlTable.deleteRow(-1);
	if (nLength == oHtmlTable.rows.length)
	{
		oHtmlTable.rows[nLength-1].outerHTML = '';
	}					
}