I have two files: a javascript file called simplecart.js, it creates a value that gets displayed in <span id="quantity" class="simpleCart_quantity"></span> in the other file I have, a html file. The html file contains this code:
<span id="quantity" class="simpleCart_quantity"></span>
<span id="quantityText"></span>
<script type="text/javascript">
var quantity = document.getElementById("quantity"),
quantityText = document.getElementById("quantityText");
if (parseInt(quantity.innerHTML, 10) === 1) {
quantityText.innerHTML = "article";
} else {
quantityText.innerHTML = "articles";
}
</script>
The problem is:
It seems as if the code can't get the value between <span id="quantity" class="simpleCart_quantity"></span> (keep in mind that that value is created in the external file simplecart.js) and now alwasy displays 'articles' because it can't see if that value is '1'.
I hope someone can help me with fixing this,
Thanks a lot!
Depending on how your simplecart.js file looks, it is highly possible that your javascript code in your html file is actually run too early (before the document is actually ready).
You should delay any DOM manipulation, e.g. with (or with jquery):
document.onload = function () {
var quantity = document .......
}
It would be better to use a binding library for that (like Angular.js) but you could update the field periodically as a quick solution:
var updatePlural = function () {
var quantity = document .......
}
setInterval(updatePlural, 250); // every 250ms
You need to delay running your JS until after the JS that populates the span with data runs.
Since your script element appears immediately after it, it is going to pull the value immediately. There is no better way to ensure that other JS doesn't run first.
The specifics of how to delay your JS until the best moment will depend on when the relevant code in simplecart.js runs,
Related
I am trying to change the value of a value of a variable, which is located within the the enqueued javascript file.
Here is my code:
- Enqueued Javascript:
jQuery(document).ready(function() {
jQuery("#adminSearch").click(function() {
var adminURL = "";
window.location = adminURL;
});
});
- Javascript on the Wordpress page:
<script>
jQuery(document).ready(function() {
var adminURL = "test.org/shop";
});
</script>
The reason I am trying to do this, is I am trying to create a function, where I can replace the url with a value assigned by the variable "adminURL" and change it's value on different Wordpress pages.
This would help make the code modular and I can use it throughout the website.
Any suggestions would be a major help!
Thanks :)
Don't quite understand why you need to do this, I think refactoring might be better but you could try using data attributes.
jQuery("#adminSearch").click(function(e) {
e.preventDefault();
var adminURL = $(this).data('adminurl');
window.location = adminURL;
)};
So you'd get the url from a data attribute on the clicked link itself instead of an attribute.
<a href="#" id="adminSearch" data-adminurl="http://test.org/shop">
This code has not been tested.
When I put this code:
window.onload = function(){
var inputs = document.querySelectorAll("input[type=text]");
console.log(inputs.length);
for(var j=0; j<inputs.length; j++){
inputs[j].onclick = function(){
this.style.width = "500px";
}
}
}
Into an html page, it works great, but if I put it into an external .js file the for loop never starts as inputs.length is equal to 0, even if in the page that calls the script there are plenty of inputs. What could be the problem?
Update:
I found out that the code works in normal conditions, but it doesn't:
on inputs that are contained in a div that was previously hidden and
then was shown via js my bad, the hidden input was of type "email"
on every input if they're loaded via ajax I found out why: since the function is fired only when the window loads, it won't see the loaded inputs
Very often, the placement of your script tag can affect your DOM selection. So make sure that your script tag is placed at the bottom of your html file just before the end of the body tag. Perhaps this will fix the issue!
Try attaching your function with addEventListener instead of setting window.onload:
window.addEventListener(function() {
//...
});
If this solves your problem then as #adeneo said, window.onload is being assigned elsewhere in the script which overwrites any other value it can have.
Which is why in general, using addEventListener is better as you can call it as many times as you want without overwriting anything.
But the problem could also simply be that your script isn't being evaluated at all, did you try putting some top-level console.log in there?
With the help of the users who commented/answered, I found out that some of the inputs I was trying the code to were of type "email" and not "text", while in other cases the inputs were loaded via ajax, so after the DOM was loaded. To fix these problems, I've edited
var inputs = document.querySelectorAll("input[type=text]");
To
var inputs = document.querySelectorAll("input[type=text],input[type=email]");
And I called again the function when the content loaded via ajax was ready.
I have tried to lead my html element to fire my customized JS file's method.
Third textarea appears nicely.
First and second textareas does not effect any of the settings i am trying to change in myJSFile.js file.
Here's my problem : js file loads the last textarea nicely, but cannot initialize previous ones properly using my js methods.
I'm doing something wrong with my JS file, and i'd appreciate if you help me.
P.S. : Initalizing some plugin and working on CKEditor.
Here's my HTML file :
<textarea id="myTextAreaID" name="myTextArea"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID')"></script>
<textarea id="myTextAreaID2" name="myTextArea2"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID2')"></script>
<textarea id="myTextAreaID3" name="myTextArea3"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID3')"></script>
Here's myJSFile.js file
var textAreaID;
$(function(){
var myTextArea = $('#'+textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param){
textAreaID = param;
}
Thanks in advance.
This is not very good idea to do it like this, however it's interesting to understand why it happens. In your code below you are defining global variable textAreaID:
var textAreaID;
$(function() {
var myTextArea = $('#' + textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param) {
textAreaID = param;
}
This script is injected three times into document. After the last script tag the value of textAreaID variable will be myTextAreaID3, because it's global and the last setTextAreaParameters invocation will override previous. Remember that scripts are loaded synchronously in your case (no async or deferred attribute), it means that onload callbacks don't wait and immediately set textAreaID to new values.
However DOMContentLoaded event has not yet fired. This is the event you are subscribing with this code:
$(function() {
// DOMContentLoaded
});
When it eventually does - only the third textarea will be processed - the one with id myTextAreaID3.
Better approach would be to have only one script tag and set textareas the same className attribute:
<textarea id="myTextAreaID2" name="myTextArea2" class="editor"></textarea>
Then in the script probably have some sort of map with configuration parameters for each individual textarea.
You are including the same script three times, but the browser is probably smart enough to only load it once (no reason to load the same script on the same page more than once).
What you need to do is to include the script only once, say before the end of the body tag
...
<script type="text/javascript" src="../public/js/myJSFile.js"></script>
</body>
and then in the JS file, wait for the document to load, and handle all text areas accordingly:
$(function() {
$('textarea').each(function(i, j) {
console.log('do something for the ' + i + 'th text area');
});
})
I am using a 3rd party app and they have a JS variable hard coded into their HTML that I need to change / update with Javascript OR jQuery, both are available to use.
The 3rd party app has variables hard coded into the page:
<script type="text/javascript" charset="utf-8">
var order_poNumber = "";
</script>
Which gets updated when a user selects a value from a dropdown (my dropdown, not 3rd party):
<script type="text/javascript" charset="utf-8">
var order_poNumber = "32380080-64060";
</script>
But the issue is that the value sticks for some reason. If you go to another page and come back (not using the back button, but by going to a different page then clicking a link to return to the order page where this issue is happening) the value is still set to 32380080-64060 but I need it to be blank as it originally was.
I've tried:
function resetPO(){
order_poNumber = "";
}
window.onload = resetPO();
And a few other variations of that, but it won't work.
I have to do the JS from an external JS file BTW.
Any ideas?
I am looking for a way to overwrite the value that is stored in the variable order_poNumber in the JS script block that is hard coded in the HTML. Ideally I want some kind of late or even delayed JS to come in and overwrite the value once the page has loaded. There are a lot of steps in how that number gets there once selected from the dropdown (AJAX, ActiveX, JS, jQuery, and a mix of 3rd party app and my own codes and functions) which took a lot of work to get working properly so I don't want to mess with all of that anymore.
The browser back button works differently than an initial page load. You can use jquery-address to add a listener to page changes (including ones from navigational arrows):
$.address.change(function(e) {
resetPO();
});
http://github.com/asual/jquery-address
Heres something I would try, just to see if it could work. We'll ask the browser to keep resetting the value until its actually reset. It does need to be executed after any script that sets the value in the first place, so maybe jQuery's ready() function is more useful than window.onload (which may already be in use by something else). Don't forget to put it before the ending </body> tag to make sure its the last thing being executed or loaded.
window.onload = function(){
var resetValueInterval = setInterval(function(){
order_poNumber = "";
if(order_poNumber == ""){
clearInterval(resetValueInterval);
}
},100);
}
You could also, instead of checking if it is set, stop checking when the value gets set. This could be never and use a lot more resources, but its always worth a try. Of course, if you reduce the amount of time between each iteration it becomes more reasonable. Not the most elegant way around the problem, but it might work.
window.onload = function(){
var resetValueInterval = setInterval(function(){
order_poNumber = "";
},100);
document.getElementById(/* order_poNumber-dropdown-id */).addEventListener("mousedown", function(){
clearInterval(resetValueInterval);
}, false);
}
I'm using the $.get() function to extract some data from my site. Everything works great however on one of the pages the information I need to extract is dynamically created and then inserted into a <div> tag.
So in the <script> tag, a function is run and then the data is inserted into <div id="infoContainer"></div>. I need to get the information from #infoContainer, however when I try to do so in the $.get() function, it just says it's empty. I have figured out that it is because the <script> tag is not being run. Is there another way to do this?
Edit:I am making a PhoneGap application for my site using jQuery to move content around so it's more streamlined for mobiles.
This is the code on my page:
$(document).ready(function () {
var embedTag = document.createElement("embed");
var infoContainer = document.getElementById("infoContainer");
if (infoContainer != null) {
embedTag.setAttribute("height", "139");
embedTag.setAttribute("width", "356");...other attributes
infoContainer.appendChild(embedTag);
});
});
As you can see, it puts content into the #infoContainer tag. However, when I try to extract info from that tag through the get function it shows it as empty.I have done the same to extract headings and it works great. All I can gather is the script tag is not firing.
This should provide you the contents of the element:
$('#infoContainer').html();
Maybe your script is executing before the DOM is loaded.
So if you are manipulating DOM elements you should wait till DOM is loaded to manipulate it. Alternately you can place your script tag at the end of your HTML document.
// These three are equivalent, choose one:
document.addEventListener('DOMContentLoaded', initializeOrWhatever);
$( initializeOrWhatever );
$.ready( initializeOrWhatever );
function initializeOrWhatever(){
// By the time this is called, the DOM is loaded and you can read/write to it
$.getJSON('/foo/', { myData: $('#myInput').val() }, onResponse);
function onResponse(res){
$(document).html('<h1>Hello '+res+'</h1>');
};
};
Otherwise... post more specifics and code
You have no ID to reference. Try setting one before you append
embedTag.setAttribute("id", "uniqueID");
It looks like you are wanting to use jQuery, but your example code has vanilla JavaScript. Your entire function can be simplified using the following jQuery (jsFiddle):
(function () {
var embedTag = $(document.createElement("embed"));
var infoContainer = $("#infoContainer");
if (infoContainer.length) {
embedTag.attr({"height": 139, "width": 356});
infoContainer.append(embedTag);
}
console.log(infoContainer.html()); // This gets you the contents of #infoContainer
})();
jQuery's .get() method is for sending GET requests to a server-side script. I don't think it does what you are wanting to do.