Syntax check - refresh div content using JavaScript and query string

Hey guys,

I don’t know how to write my own JavaScript from scratch, but I think I am close to what I need with these two snippets of code.

When I click anywhere on a certain page, I want the contents of a specific div to change depending on the query string present in the URL.

I have some code which achieves this, but in this format, it only works of the entire page gets refreshed.

Here is the working code which I have tested:


The problem is, I am using a filter system which alters the URL with a query string without refreshing the page, so the code above is not triggered.

From my understanding, I think I need to incorporate a mousedown event, e.g.

document.addEventListener(“mousedown”, function(){
console.log(“You did it!”);
});

I’m wondering how I can incorporate the mousedown event to run the code above when a user clicks anywhere on the page. I don’t know how to write the correct syntax for this.

I’m also wondering if I can be more specific with the mousedown event, for example can I trigger the code if a specific element is clicked (or checked), such as: input[type=checkbox]

Thanks in advance for any advice or help you can give.

You dont includes the code

Hi Paolo,

Apologies, I did paste it in but somehow it has disappeared. I will try again:

<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
	// Parse the URL parameter
	function getParameterByName(name, url) {
	    if (!url) url = window.location.href;
	    name = name.replace(/[\[\]]/g, "\\$&");
	    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
	        results = regex.exec(url);
	    if (!results) return null;
	    if (!results[2]) return '';
	    return decodeURIComponent(results[2].replace(/\+/g, " "));
	}
	// Give the parameter a variable name
	var dynamicContent = getParameterByName('dc');

	 $(document).ready(function() {

		// Check if the URL parameter is apples
		if (dynamicContent == 'apples') {
			$('#apples').show();
		} 
		// Check if the URL parameter is oranges
		else if (dynamicContent == 'oranges') {
			$('#oranges').show();
		} 
		// Check if the URL parameter is bananas
		else if (dynamicContent == 'bananas') {
			$('#bananas').show();
		} 
		// Check if the URL parmeter is empty or not defined, display default content
		else {
			$('#default-content').show();
		}
	});
</script>

Many thanks!

Here is the working code I tested which is missing from above.
Many thanks!

<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
	// Parse the URL parameter
	function getParameterByName(name, url) {
	    if (!url) url = window.location.href;
	    name = name.replace(/[\[\]]/g, "\\$&");
	    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
	        results = regex.exec(url);
	    if (!results) return null;
	    if (!results[2]) return '';
	    return decodeURIComponent(results[2].replace(/\+/g, " "));
	}
	// Give the parameter a variable name
	var dynamicContent = getParameterByName('dc');

	 $(document).ready(function() {

		// Check if the URL parameter is apples
		if (dynamicContent == 'apples') {
			$('#apples').show();
		} 
		// Check if the URL parameter is oranges
		else if (dynamicContent == 'oranges') {
			$('#oranges').show();
		} 
		// Check if the URL parameter is bananas
		else if (dynamicContent == 'bananas') {
			$('#bananas').show();
		} 
		// Check if the URL parmeter is empty or not defined, display default content
		else {
			$('#default-content').show();
		}
	});
</script>

Post the whole code please. Cant find the problem without seeing the html

Hi Paolo,

Here is the full code which works to show content based on the present query string. It need the page to be refreshed for it to run. I would like to incorporate the mousedown event so the code runs when a user clicks inside the page:

Show/hide dynamic content based on URL parameters

The HTML
Wrap each one of your dynamic content sections in a DIV and add a class called dynamic-content. Also, give each DIV a unique ID. We will reference these later in the JavaScript.


<!-- Default Dynamic Section -->
<div id="default-content" class="dynamic-content">
  This is the default content
</div>
<!-- Dynamic Section 1 -->
<div id="apples" class="dynamic-content">
  I like apples
</div>
<!-- Dynamic Section 2 -->
<div id="oranges" class="dynamic-content">
  I like oranges
</div>
<!-- Dynamic Section 3 -->
<div id="bananas" class="dynamic-content">
  I like bananas
</div>

The CSS
There’s only one line of CSS needed to hide all the elements on the page since JavaScript will be used to show/hide the content.

.dynamic-content {
    display:none;
}

The JavaScript
This is the complicated part. First, we need to parse the URL and check for a specific parameter. For this example I will be using the parameter name “dc”, so in this case, my URL would look like this:

https://jennamolby.com/my-webpage?dc=mycontent

This is the piece of code to parse the URL. You can change “dc” to be whatever parameter name you want.

<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
	// Parse the URL parameter
	function getParameterByName(name, url) {
	    if (!url) url = window.location.href;
	    name = name.replace(/[\[\]]/g, "\\$&");
	    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
	        results = regex.exec(url);
	    if (!results) return null;
	    if (!results[2]) return '';
	    return decodeURIComponent(results[2].replace(/\+/g, " "));
	}
	// Give the parameter a variable name
	var dynamicContent = getParameterByName('dc');

	 $(document).ready(function() {

		// Check if the URL parameter is apples
		if (dynamicContent == 'apples') {
			$('#apples').show();
		} 
		// Check if the URL parameter is oranges
		else if (dynamicContent == 'oranges') {
			$('#oranges').show();
		} 
		// Check if the URL parameter is bananas
		else if (dynamicContent == 'bananas') {
			$('#bananas').show();
		} 
		// Check if the URL parmeter is empty or not defined, display default content
		else {
			$('#default-content').show();
		}
	});
</script>

Many thanks for looking!

I dont really understand what youre trying to do.
If you want to show the div based onnthe parameter in the url you dont need a click event listener .
When the page load the callback watch for the parameter in the url and show the div with that id.
Dont get the point to showing a div when clicking on the page.
Could you explain what you re trying to achieve?

Hi Paulo,
Many thanks for your reply. I am using a filter system on a test page:

The filter system refreshes the page URL and adds query strings based on checkboxes and other filtering options. The page then shows the relevant products without reloading.
I wish to show a div containing a description for whichever product category is selected. If a category is selected, the div should be visible (above the search tools and product grid).
If a category gets de-selected, the corresponding div should be hidden.
I tried a tweak to the code I am using, but it still doesn’t work properly.
I will post all code used below that is active on the test page:

JavaScript

   <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
    <script type="text/javascript">
    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }
    
    function parseDynamicContent() {
        // Give the parameter a variable name
        var dynamicContent = getParameterByName('tex_project_category');
    	// Check if the URL parameter is breast-positioning
    	if (dynamicContent == 'breast-positioning') {
    		$('#breast-positioning').show();
    	} 
    	// Check if the URL parameter is couchtops-overlays
    	else if (dynamicContent == 'couchtops-overlays') {
    		$('#couchtops-overlays').show();
    	} 
        // Check if the URL parameter is fiducial-markers
        else if (dynamicContent == 'fiducial-markers') {
            $('#fiducial-markers').show();
        }
        // Check if the URL parameter is head-neck-positioning
        else if (dynamicContent == 'head-neck-positioning') {
            $('#head-neck-positioning').show();
        }
        // Check if the URL parmeter is empty or not defined, display default content
        else {
            $('#default-content').show();
        }
    }
    
    $(document).ready(function () {
        parseDynamicContent()
    
    });
    document.addEventListener("mousedown", function () {
        parseDynamicContent()
    });
    </script>type or paste code here

HTML

    <!-- Default Dynamic Section -->
    <div id="default-content" class="dynamic-content">This is the default content and should be hidden if one of the search filters is ticked</div>
    <!-- Dynamic Section 1 -->
    <div id="breast-positioning" class="dynamic-content">
    <h3>Breast Positioning</h3>
    This content should only show if the Breast Positioning filter box is checked</div>
    <!-- Dynamic Section 2 -->
    <div id="couchtops-overlays" class="dynamic-content"><strong>Couchtops Overlays</strong>
    This content should only show if the Couchtops Overlays filter box is checked</div>
    <!-- Dynamic Section 3 -->
    <div id="fiducial-markers" class="dynamic-content"><strong>Fiducial Markers</strong>
    This content should only show if the Fiducial Markers filter box is checked</div>
    <!-- Dynamic Section 4 -->
    <div id="head-neck-positioning" class="dynamic-content"><strong>Head and Neck Positioning</strong>
    This content should only show if the Head and Neck Positioning filter box is checked</div>

And the CSS which is no longer working to hide dynamic data which isn’t selected:

        .dynamic-content {
        display:none;
    }

I hope this now makes more sense.
Best wishes,
Lanx

The jQuery .show() method adds display: block as an inline style which will overwrite any selector (except when using !important).

You can use the .hide() method which adds display: none as an inline style.

There is also .toggle() which does both.

I didn’t really look at your code but I assume you can do it conditionally or just loop all the elements and hide them before the conditions that show each individual one.

1 Like

Thanks Lasjorg,

I think it is time for me to dig deeper into the solutions you suggest. I may be approaching this in the wrong way. Thanks for your input.

Best wishes,
Lanx

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.