Changing the value of enqueued Javascript - javascript

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.

Related

Javascript element tag name undefined

So I'm not that great with Javascript so I'll put that forward right away. That being said, I've looked up as much as I could on this particular problem before asking, but the suggestions haven't solved my issues. I'm ultimately trying to pull all of the links from an iframe window on the same domain as the main page. Then I want to basically search that link array to match it with the current page to trigger a CSS modification to the html code (this part is not coded yet, FYI). So here is the part I have so far: Side note: The confirms are in there to debug the code and try to tell me where it's failing and what my queries are returning, they won't stay obviously when this is finished. I appreciate any advice that may help me fix this!
<script type="text/javascript">
// main is the iframe that I'm trying to search for a tags
document.getElementById("main").onload = function() {
confirm("test");
var main = document.getElementById("main");
var anchors = main.contentWindow.document.getElementsByTagName('a');
confirm(anchors[1]);
for (var i in anchors) {
confirm(anchors[i].getAttribute("href"));
}
};
</script>
I have created a plunker for you its working. I think its the placement of code in your file is causing the problem.
<iframe id="main" src="content_if.html"></iframe>
<script>
// main is the iframe that I'm trying to search for a tags
document.getElementById("main").onload = function() {
confirm("test");
var main = document.getElementById("main");
var anchors = main.contentWindow.document.getElementsByTagName('a');
confirm(anchors[1]);
for (var i in anchors) {
confirm(anchors[i].getAttribute("href"));
}
};
</script>
You should use jQuery to do this in a cross browser way. Include jQuery in page
<script src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
and follow this post
There is a similar post about doing this and I agree with Mohamed-Yousef. If you can use jquery then you should do so!
$("#main").contents().find("a").each(function(element) {
// "each" will iterate through every a tag and inject them as the "element" argument
// visible in the scope of this anonymous function
});
EDIT:
You must include
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
above your code that references the $ variable. There are other ways to use jQuery but this is probably the easiest.

Using <span> value that is created in an external file

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,

Site is scrolling down automatically aftear search

This is my site URL which is developed in magento(www.theprinterdepo.com), when a user searches, the page automatically scrolls down to the bottom. I have no idea if this due to any php code, jquery or javascript but I need help to detect and fix this.
I would paste code here, but I don't know what's responsible for this behaviour.
I thought it was IE problem, but its also reflects in Google Chrome.
thanks
<script type="text/javascript">window.onload=function()
{
var deftxt='Test';
var def=document.getElementById('ea');
def.onfocus = function()
{
this.value=(this.value==deftxt)?'':this.value;
}
def.onblur= function()
{
if(this.value=='')
{
this.value=deftxt;
}
else
this.value;
}
***def.focus();***
def.blur();
}</script>
Here the textbox having id "ea" is set focus on. Please remove "def.focus();". Your issue will be solved.
Remove def.focus() from your script tag in the footer.
Perhaps unrelated - but unless I am mistaken - you have an accidental closure/circular reference. When you reference a JS object that contains a reference to a DOM object, which in turn references the JS object - you have a closure that creates a circular reference. In this case def.onBlur() / def.blur() is the culprit. (See the code below - a textbook example of a circular reference.) Not sure if this is causing your issue, but this is definitely something I would look into.
<script>
myFunction(){
var elObj = document.getElementById('myDiv');
elObj.onclick= function() {
alert('This function is leaking.');
}}
myFunction();
</script>

Scripts not running when using get function in jquery

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.

Ajax inserted content not accessible in DOM

I am working on a pure jquery/js site, mostly to practice some jquery. I am using a load statement to load a menu from a file of common html, like so:
$('#categoryListing').load('../common.html #categoryLinksUL');
which loads:
<ul id="categoryLinksUL">
<li>Anklets</li>
<li>Bracelets</li>
</ul>
The problem is where I am using it now I need to alter the href of the above links, but they are not part of the dom. In previous instances I was able to use .live(click... But not here. Is there a way I can accomplish this?
Specifically I need to load the links and change the href from #anklets to ?category=anklets
What about the following?
$('#categoryListing').load('../common.html #categoryLinksUL', function() {
$('li a[href^="#"']').each(function () {
this.href = '?category=' + this.href.substr(1);
});
});
In my example, after the load is completed, the anonymous function is called. It takes every anchor with a hash HREF and replaces it with an HREF based on your description.
Thank you Dimitry, you solution basically worked. I finally used:
$('#categoryListing').load('../common.html #categoryLinksUL', function() {
$('#categoryListing li a').each(function () {
var hashPos=this.href.indexOf("#");
var tCategory = this.href.substr(hashPos+1,this.href.length );
});
});
So why did jQuery recognize categoryListing there? I tried moving the each function outside of the load function and categoryListing did not contain any links. Is it because maybe the load was not completed when it tried to get categoryListing links? Seems like that is possible.
Thanks,
Todd

Categories