Toggle Visibility of Separate Javascript Files on Same Wordpress Page - javascript

Let me preface by saying this is all in relation to a Wordpress page. My knowledge of JS is lacking at best and the concept of installing/loading/enqueueing a function on one area of the site and then calling that function in another area of the site is a something that makes sense to me in my head but is very new to me in practice and might need a little explaining.
I have two separate javascript files that I would like to load on a single page, but toggle visibility/display of either based on radio button input. The JS is provided by a 3rd party and is offsite. Their provided code is this:
<script src="https://toolkit.rescuegroups.org/j/3/FzemP6HU/toolkit.js"></script>
and
<script src="https://toolkit.rescuegroups.org/j/3/4ANRW3x8/toolkit.js"></script>
Each file presents a separate set of filtered results from their database. How can I incorporate both onto a page but only have one or the other showing based on a radio button form input? I would like the page to start off with nothing visible (hopefully giving time for both JS to load in the background while the user selects an option) and then show one or the other depending on what they selected.
You can see a single one of these in action at http://pricelesspetrescue.org/adoptable-dogs/. I'm trying to incorporate the use of an additional file on that same page based on input from the user and only showing one or the other rather than both.
I have tried to manage the following
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<script type='text/javascript'>
function displayForm(c) {
if (c.value == "2") {
jQuery('#claremontdogContainer').toggle('show');
jQuery('#chdogContainer').hide();
}
if (c.value == "1") {
jQuery('#chdogContainer').toggle('show');
jQuery('#claremontdogContainer').hide();
}
};
</script>
<label>Please select a location to view:</label>
<form>
<input value="1" type="radio" name="formselector" onClick="displayForm(this)"></input>Chino Hills
<input value="2" type="radio" name="formselector" onClick="displayForm(this)"></input>Claremont
</form>
<div style="display:none" id="chdogContainer">
<script src="https://toolkit.rescuegroups.org/j/3/FzemP6HU/toolkit.js"></script>
<script type="text/javascript">
</script>
</div>
<!-- If I uncomment this second block the whole thing breaks
<div style="display:none" id="claremontdogContainer">
<script src="https://toolkit.rescuegroups.org/j/3/4ANRW3x8/toolkit.js"></script>
<script type="text/javascript">
</script>
</div>
-->
This gets pretty close to what I need. The problem I have is the second script load seems to conflict with the functions they provide in the script. It will display the initial result but does not carry any of the functionality that it should have. http://pricelesspetrescue.org/test-page/ Nothing is clickable inside those results and should be.
Been searching through various similar posts and the wordpress codex and...and...I just haven't been able to come up with anything that seems close enough to what I'm looking for to make the answer click in my head.
Edit: It seems that if I only load one of the scripts in either what I have above or the suggested answer below, all functionality is present when loaded. It's the loading of the second toolkit script that is breaking the page. I'm guessing one would need to be loaded then unloaded before loading the second for it to work. Any ideas?

The toolkit.js file you linked adds some common scripts to the DOM (via document.write function, which is not a good solution - see here: http://www.jameswiseman.com/blog/2011/03/31/jslint-messages-document-write-can-be-a-form-of-eval/), then populates an array (toolkitObjects) with a series of variables that are custom per file and finally loads some other scripts.
It also seems that each file loads a div with a specific class containing all the pets, and each div is identifiable by a specific class ( "rgtk-SOMEID" ) and therefore can be shown/hidden via javascript.
Here is an example of what you can obtain using the div class:
http://jsbin.com/loneyijuye/edit?html,output

Related

how to store content that is displayed dynamically

I was wondering what is the proper way of store in html content that is displayed dynamically.
My case is that depending on what is clicked some sort of text is displayed in another part of a website. My first idea was to create a variable in js/jquery script to store this content so the script can access it whenever it is necessary.
this is an example:
var someContent=" Content to be displayed when something is clicked";
var a=$('#myid');
a.click(function(){
$('#myOtherId').text(someContent);
});
But after a while it came to my mind that the content should be stored in the html with a display value set to 'none' and js script should simple toggle its visibility depending wether it has been clicked or not.
Storing the content in js script seems much easier - but something tells me that there is better way to do it...
Indeed, you can do it by having the text in an HTML element, and use either jQuery's .toggle or .show depending on how you want it to respond to a second click:
$("#toggle").click(function () {
$('#msg').toggle(); // or .show() to have it in one way only
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="msg" style="display:none">Content to be displayed when something is clicked</span>
<br>
<button id="toggle">click me</button>
When the content is static, it seems more natural to have it embedded in your HTML, while when the content is dynamic (i.e. it depends on the actual state of the application), you would inject the dynamic part of the text with JavaScript.
For a non-JS-programmer in the development team (but with knowledge of HTML) it would in theory be easier to manipulate the messages when they are embedded in the HTML part of the page.
But this is a matter of opinion really.
Here is a mix of the two:
$("#enter").click(function () {
// Copy the number into the error message
$('#num').text($("#inp").val());
// Show the error message when the number is not even
$('#msg').toggle($('#inp').val() % 2 !== 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter an even number: <input id="inp" type="number" value=1>
<button id="enter">Verify</button>
<div id="msg" style="display:none; color:red">
The number <span id="num"></span> is not even
</div>

Loading dynamic contents when a div is clicked

I hope you can help me with this.
I would like to use a dynamic call to the server to get the content that needs to be loaded to a div.
There is a fixed menu at the bottom of the page that when tag is clicked calls a function and tells it which frame to update, and then in the function generates an XMLHttpRequest (or use ActiveX in case of old IE versions etc.), with that request navigate to a predefined location on the server where the php snippet lies that needs to be included, and then set that as the innerHTML of the corresponding output section.
I also would like an array outside of the function that keeps track of which pages have already been loaded, so that it doesn't load a page again just because a user clicks on the link a second time.
HTML:
<div id="FixedMenu">
<input type="radio" name="radio-set" checked="checked" id="main"/>
Main
<input type="radio" name="radio-set" id="2nd"/>
2nd
<input type="radio" name="radio-set" id="3rd"/>
3rd
<input type="radio" name="radio-set" id="4th"/>
4th
<input type="radio" name="radio-set" id="4th"/>
4th
</div>
<div class="scroll">
<section class="main">
<!-- loads the main context. -->
</section>
<section id="2nd" >
<!-- this section should load the php file only when the button is clicked. -->
</section>
<!-- section 3rd - 5th... -->
</div>
JAVASCRIPT
<script>
$(document).ready(function(){
$("#2").click(function(){
$("#2nd").load('MyURL');
});
});
</script>
Is there any chance I can put a php file in the same folder here instead of directing the function to an url?
You should be able to do this:
$("#2nd").load('/path/to/my/php/page/here');
Have you tried that
What you try is the right way.
$("#2nd").load('MyURL');
'MyUrl' should contain your link to your php file, relative to your current file.
If you want to cache the content, you could simply use the second parameter of load named data to save your content.
According to this documentation it appears that you can. It's still a URL though, as jQuery will still an AJAX request to fetch the given resource. Keep in mind that you want this, as your PHP server does need to parse the file in order to behave like PHP.
$('.content').load('dynamic_content.php');
In response to poster's comment:
Pay particular attention to the part of the documentation that regards to loading page fragments.
$( "#result" ).load( "ajax/test.html #container" );
Although PHP will still have to parse the entire requested script you can render only a specific portion of it using this syntax and that may help speed things up slightly.
Another thought may be not pointing to a full page, but to an API end point that would return the data you are looking for. This can avoid extra logic for the full page and/or return JSON data for easier JS work.

Script to pick up the HTML value of a page? Explanation inside

I am quite the noob at anything other than some HTML, CSS etc, basic website stuff. My javascript is pretty non-existant too. However we were quoted £2,500 by the people who develop our website to add Paypal on the checkout page! They use a fancy 3rd party program which is a standalone software made by themselves that contains all the products etc. We pay monthly to have access to that and make all website changes (such as price, product name etc) in that.
To cut a long story short, I had a look around and found this:
<script src="paypal-button.min.js?merchant=YOUR_MERCHANT_ID"
data-button="buynow"
data-name="My product"
data-amount="1.00"
async
></script>
Now, can I change the data-amount field to pick up what the "value" is on the page in the HTML? That way I can simply just add a button that picks that up. Which would work with paypal.
<div class='basketLabel'>Total Amount To Pay:</div>
<span>£</span>1,038.00</li>
<input type=hidden name='amount' value='1,038.00'>
Basically, how can I get the javascript code to pick up the value from the HTML (or somewhere else). I only have access to the full HTML of the page.
I am not sure how many of these data fields you have on a page but you could write a JS method to dynamically assign the values of the given HTML.
I would start by giving the HTML you're working with some ID's.
<script id="paypalScript" src="paypal-button.min.js?merchant=YOUR_MERCHANT_ID"
data-button="buynow"
data-name="My product"
data-amount="1.00"
async
onload="assignAmount"
></script>
<div class='basketLabel'>Total Amount To Pay:</div>
<span>£</span>1,038.00</li>
<input id="amount" type=hidden name='amount' value='1,038.00'>
Then write a method to execute onload.
function assignAmount(){
var amtElm = document.getElementById('amount');
var scriptElm = document.getElementById('paypalScript');
scriptElm.dataset.amount = amtElm.value;
}
Then attach the method to the onload event of the script element. Putting the script tag below your data field in the HTML should prevent any load issues you might run into.

document.ready working only once on page load

I have the following code in a .tpl file ("comment_form.tpl"). This file is included in 3 different .tpl files ("file_a", "file_b" and "file_c") once each. And finally these 3 files are included in another .tpl file ("somefile.tpl").
<script type="text/javascript">
$(document).ready(function Hide() {
document.getElementById('div').style.display = 'none';
</script>
So basically, the "comment_form.tpl" is loaded thrice in "somefile.tpl" like so:
.....
</div><!-- .span9 -->
{include file="includes/file_a.tpl"} // includes "file_a.tpl" which already includes "comment_form.tpl" (which contains the code).
</div>
.....//some code
{include file="includes/file_b.tpl.tpl"} // "includes file_b.tpl" which already includes "comment_form.tpl" (which contains the code).
The issue is, the code works the first time. As in, out of the three places where the "comment_form.tpl" is loaded in "somefile.tpl", the target 'div' is hidden only the first time. At the next two places the form (div) isn't hidden.
I hope I am clear enough. What could be the reason??
It is perfectly legal to have multiple $(document).ready(function() {}) calls throughout your page.
It seems that you are hiding your element by ID. Note that IDs must be unique, and if you use the same ID multiple times (#div in your example), only ever the first is selected by getElementById(). That's what you are experiencing.
You must give each <div> a unique ID or group them together with a CSS class and hide the whole class.
Here is an example using a CSS class:
<div class="comment_form">some content</div>
<div class="comment_form">some content</div>
<div class="comment_form">some content</div>
<script type="text/javascript">
$(document).ready(function () {
$('.comment_form').css({'display' : 'none'});
}
</script>
By the way it's far more efficient to directly use CSS for the initial 'hidden' state of your <div>. There is no need to execute JavaScript on page load at all:
<style>
.comment_form { display: none; }
</style>
<div class="comment_form">some content</div>
You can still change the display property of your element later via JavaScript in an onClick event, for example.

Display element from other page on my site with .document.getElementById

I have been searching about this subject now for quite a few days. And could not find a working or conclusive answer.
What I want to do, is to simply display the (styled) summary of the latest blog entry (from the blog page on my own site) in a div container on the front page of my site (which is not my blog). All active links of that mirrored blog entry ideally lead to the appropriate section of my blog page. That is however not a must, as long as the entire entry can link to the blog page.
Each blog entry summary on the blog summary page has a unique ID, sorted by numbers (e.g. unique-ID-51 (latest) unique-ID-50 (the one before) etc.)
I was thinking of doing so with the document.getElementById JS command.
I would have to point the JS function to a relative location (../blog_folder/blog_summary.html) with maybe the .window.location.assign
command, than grab the (styled) contents of the latest element and display that on my front page.
But I have no idea how that code would look in reality. Can you point me in the right direction?
Thank you !!!!!!!
M.
You could add jQuery to your page and use a simple construction:
$('.result-container').load('path/to/your/file.html #id_of_element_to_fetch');
An example chunk of code:
...
<body>
<div class="result-container">There will be your content from some file.</div>
<p>
<a class="result-loader" href="#"></a>
<script type="text/javascript">
$(".result-loader").click(function() {
//Replace path/to/your/file.html and #id_of_element_to_fetch with appropriate values
$('.result-container').load('path/to/your/file.html #id_of_element_to_fetch');
return false;
});
</script>
</p>
</body>
...
And that string somewhere inside the <head> tag:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
An example chunk of code with an autostart feature:
...
<body>
<div class="result-container">There will be your content from some file.</div>
<p>
<a class="result-loader" href="#"></a>
<script type="text/javascript">
$(document).ready(function() { //Launches the code below right after the initialization event
//Replace path/to/your/file.html and #id_of_element_to_fetch with appropriate values
$('.result-container').load('path/to/your/file.html #id_of_element_to_fetch');
return false;
});
</script>
</p>
</body>
...
I assume you are using a hidden iframe?
This for example will thet the height of the style.. there are other things in the style
this.container.getElementsByTagName("YOUuniqueID")[0].style.(STYLE)
But you have to put an unique ID in the iframe
Try and use the built in debuggers in IE or Chrome to find what you want...
You can take a look at this for maybe some more info(its for cross domain) but there could be something taht helps you. You might even consider using jquery to access that data.
Yet Another cross-domain iframe resize Q&A

Categories