I am running this code in Chrome console dev tools and it works:
const params = new URLSearchParams(window.location.search);
if (window.location.href.indexOf("Phone") != -1) {
$('.test111232 a').attr('href', 'tel:1 ' + params.get('Phone'));
}
if (window.location.href.indexOf("state") != -1) {
$('.test111232234 a').attr('href', 'https://www.example.com/ddd?state=' + params.get('state'));
}
However, when I save the page on WordPress with the Elementor HTML widget, it only changes the first number on the page.
Any ideas?
ok so basically what fixed the error was to add this:
$(document).ready(function()
before the code above, so it looks like this:
<script>
$(document).ready(function() {
const params = new URLSearchParams(window.location.search);
if (window.location.href.indexOf("Phone") != -1) {
$('.test111232 a').attr('href', 'tel:1 ' + params.get('Phone'));
}
if (window.location.href.indexOf("state") != -1) {
$('.test111232234 a').attr('href', 'https://www.example.com/ddd?state=' + params.get('state'));
}
});
</script>
one side point that might be relevant. I had an older version of elementor pro which could be impacting js loading through the html widget.
I had the script opening and closing tags but for some reason it wanted the function and then it worked. Could be that's the way it's suppose to be in the first place.
Related
I have been struggling ajaxing my website, which happens to be a WordPress.
What I am trying to do, is to only refresh the content of my blog. What I mean is that my header, footer # sidebar shouldn't be refreshed when I navigate through my website.
It sounded easy to me when I first started, but I was wrong. I've been looking around to find a way to get around problems and found this but it did not help... So, here is my terrible issue :
There are Javascript scripts that are involved in my "refreshed content" and the innerHTML does not keep the JS. Only Html is transposed... As a result, my plugins aren't working anymore.
So, I have been looking for a way to keep the JS content.
I hope I have been clear in desribing my problems and pray for you guys to be able to help me :)
Here is my website : www.construction.urbaineparis.com
If you need more details, I will be very willing to give you the code you need to help.
Here is a part of the source that I believe contains the issue.
//start changing the page content.
jQuery('#' + AAPL_content).fadeOut("slow", function() {
//See the below - NEVER TRUST jQuery to sort ALL your problems - this breaks Ie7 + 8 :o
//jQuery('#' + AAPL_content).html(AAPL_loading_code);
//Nothing like good old pure JavaScript...
document.getElementById(AAPL_content).innerHTML = AAPL_loading_code;
jQuery('#' + AAPL_content).fadeIn("slow", function() {
jQuery.ajax({
type: "GET",
url: url,
data: getData,
cache: false,
dataType: "html",
success: function(data) {
AAPL_isLoad = false;
//get title attribute
datax = data.split('<title>');
titlesx = data.split('</title>');
if (datax.length == 2 || titlesx.length == 2) {
data = data.split('<title>')[1];
titles = data.split('</title>')[0];
//set the title?
//after several months, I think this is the solution to fix & issues
jQuery(document).attr('title', (jQuery("<div/>").html(titles).text()));
} else {
if (AAPL_warnings == true) {
alert("WARNING: \nYou seem to have more than one <title> tag on the page, this is going to cause some major problems so page title changing is disabled.");
}
}
//Google analytics?
if (AAPL_track_analytics == true) {
if(typeof _gaq != "undefined") {
if (typeof getData == "undefined") {
getData = "";
} else {
getData = "?" + getData;
}
_gaq.push(['_trackPageview', path + getData]);
} else {
if (AAPL_warnings == true) {
alert("WARNING: \nAnalytics does not seem to be initialized! Could not track this page for google.");
}
}
}
///////////////////////////////////////////
// WE HAVE AN ADMIN PAGE NOW - GO THERE //
///////////////////////////////////////////
try {
AAPL_data_code(data);
} catch(err) {
if (AAPL_warnings == true) {
txt="ERROR: \nThere was an error with data_code.\n";
txt+="Error description: " + err.message;
alert(txt);
}
}
//get content
data = data.split('id="' + AAPL_content + '"')[1];
data = data.substring(data.indexOf('>') + 1);
var depth = 1;
var output = '';
while(depth > 0) {
temp = data.split('</div>')[0];
//count occurrences
i = 0;
pos = temp.indexOf("<div");
while (pos != -1) {
i++;
pos = temp.indexOf("<div", pos + 1);
}
//end count
depth=depth+i-1;
output=output+data.split('</div>')[0] + '</div>';
data = data.substring(data.indexOf('</div>') + 6);
}
//put the resulting html back into the page!
//See the below - NEVER TRUST jQuery to sort ALL your problems - this breaks Ie7 + 8 :o
//jQuery('#' + AAPL_content).html(output);
//Nothing like good old pure JavaScript...
document.getElementById(AAPL_content).innerHTML = output;
Change
document.getElementById(AAPL_content).innerHTML = AAPL_loading_code;
to
$("#"+AAPL_content).html(AAPL_loading_code);
jQuery takes care of executing scripts that are in the HTML, which .innerHTML does not do.
I doubt this really breaks in IE 7, as your comment says, unless you're using jQuery 2.x (they've dropped support for old IE versions).
I've built a site that uses the History.js plugin to navigate from page to page with AJAX and update the URL accordingly. All works well except in IE; when you refresh the page it essentially loads the content from the first page you came to, not the current pages content. In "decent" browsers it doesn't load the content from any page, it just loads the entire page for that URL, which is what I IE should do.
I'm thinking it doesn't understand what to do with the hash. If you visit http://www.crownacre.voyced.com/contact-us/ it works fine, but when you visit http://www.crownacre.voyced.com/#contact-us/ (with the hash) it doesn't.
I've attempted to redirect the page if it detects a # in the pathname, but there is no way of detecting this as window.location.pathname and History.getHash() returns the path without any hash.
Any suggestions? I've seen a few websites using this plugin that have the same problem, and similar issues on here, but no solution.
Thanks in advance!
I ran into the same problem in my rewrite of tarheelreader.org. I'm using History.js and it is working fine except for the refresh issue in IE8. This hack is working for me.
In my startup code that only runs on initial page load I do:
var url = window.location.href;
if (url.indexOf('#') > -1) {
// ie refresh hack
controller.stateChange();
}
where controller.stateChange() is the state change handler I use for all History changes.
function stateChange() {
// handle changes in the URL
var hist = History.getState(),
url = hist.url,
context = hist.data;
renderUrl(url, context).then(function(title) {
document.title = title;
});
}
You can see all the code in main.js and controller.js at https://github.com/gbishop/TarHeelReaderTheme
Edit
Further exploration has lead to a case where History.js uses the initial URL instead of the root. This hack seems to handle that case.
function stateChange() {
// handle changes in the URL
var hist = History.getState(),
url = hist.url,
bar = window.location.href,
context = hist.data;
//console.log("State changed...", url, context);
if (url != bar && bar.indexOf('#') > -1) {
//console.log('bar = ', bar);
// I think we only get here in IE8
// hack for hash mode urls
var root = History.getRootUrl(),
hashIndex = bar.indexOf('#');
if (root != bar.slice(0, hashIndex)) {
// try to fix the url
url = root + bar.slice(hashIndex);
//console.log('new url =', url);
window.location.href = url;
}
}
renderUrl(url, context).then(function(title) {
document.title = title;
});
}
This worked for me:
<script>
var url = new String(document.location);
if (url.indexOf("#") > -1) {
alert("There is a Hash in the path");
}
</script>
Edit:
function LocationTest()
{
var loc = window.location;
alert(loc.href);
alert(loc.protocol + "//" + loc.host + loc.pathname + loc.search + loc.hash);
alert(loc.href == loc.protocol + "//" + loc.host + loc.pathname + loc.search + loc.hash);
}
Sample Source: window.location explained
Maybe a solution:
Can you please try the History.js unofficial version 1.8a2 of my fork from:
https://github.com/andreasbernhard/history.js
...and give feedback? Thank you very much!
I am trying to dynamically adjust the height of an iFrame on a web page depending on the content within the iFrame via some JavaScript.
My problem is when I have the script directly on the page in a <script> tag it works fine. When I stuff the code in to a separate js file and link to it- it doesn't work!
<iframe id='StatusModule' onload='FrameManager.registerFrame(this)' src='http://randomdomain.dk/StatusModule.aspx'></iframe>
<script type='text/javascript' src='http://randomdomain.dk/FrameManager.js'></script>
It gives me the error:
Uncaught ReferenceError: FrameManager is not defined
Can this really be true? Has it something to do with the page life cycle?
Ps. I guess the JavaScript code is irrelevant, as we not it works.
UPDATE: I think this might have something to do with secure http (https) and the different browsers in some weird way. I noticed that the script actually worked in Firefox. Or rather I'm not sure if its the script, or just Firefox's functionality that resizes iframes automatically depending on the content. It doesn't give me any error though.
If I then add https to the script url reference, the scripts work in IE and Chrome - but not in Firefox. Function reference error! This just got weird!
UPDATE #2: Its not a Firefox function that resizes the iframe. Its the actual script that works (without https).
UPDATE #3: The JavaScript. Works fine if I put it directly into a script tag.
var FrameManager = {
currentFrameId: '',
currentFrameHeight: 0,
lastFrameId: '',
lastFrameHeight: 0,
resizeTimerId: null,
init: function () {
if (FrameManager.resizeTimerId == null) {
FrameManager.resizeTimerId = window.setInterval(FrameManager.resizeFrames, 0);
}
},
resizeFrames: function () {
FrameManager.retrieveFrameIdAndHeight();
if ((FrameManager.currentFrameId != FrameManager.lastFrameId) || (FrameManager.currentFrameHeight != FrameManager.lastFrameHeight)) {
var iframe = document.getElementById(FrameManager.currentFrameId.toString());
if (iframe == null) return;
iframe.style.height = FrameManager.currentFrameHeight.toString() + "px";
FrameManager.lastFrameId = FrameManager.currentFrameId;
FrameManager.lastFrameHeight = FrameManager.currentFrameHeight;
window.location.hash = '';
}
},
retrieveFrameIdAndHeight: function () {
if (window.location.hash.length == 0) return;
var hashValue = window.location.hash.substring(1);
if ((hashValue == null) || (hashValue.length == 0)) return;
var pairs = hashValue.split('&');
if ((pairs != null) && (pairs.length > 0)) {
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
if ((pair != null) && (pair.length > 0)) {
if (pair[0] == 'frameId') {
if ((pair[1] != null) && (pair[1].length > 0)) {
FrameManager.currentFrameId = pair[1];
}
} else if (pair[0] == 'height') {
var height = parseInt(pair[1]);
if (!isNaN(height)) {
FrameManager.currentFrameHeight = height;
//FrameManager.currentFrameHeight += 5;
}
}
}
}
}
},
registerFrame: function (frame) {
var currentLocation = location.href;
var hashIndex = currentLocation.indexOf('#');
if (hashIndex > -1) {
currentLocation = currentLocation.substring(0, hashIndex);
}
frame.contentWindow.location = frame.src + '&frameId=' + frame.id + '#' + currentLocation;
}
};
window.setTimeout(FrameManager.init, 0);
UPDATE #4: Alright I did as ShadowWizard and TheZuck suggested:
<script type="text/javascript">
var iframe = document.createElement("iframe");
iframe.src = "http://www.randomdomain.dk/StatusWebModule.aspx";
iframe.width = '100%';
iframe.id = 'StatusModule';
iframe.scrolling = 'no';
if (iframe.attachEvent) {
iframe.attachEvent("onload", function () {
FrameManager.registerFrame(iframe);
});
} else {
iframe.onload = function () {
FrameManager.registerFrame(iframe);
};
}
document.getElementById('framecontainer').appendChild(iframe);
</script>
With HTTP as URL its work on IE and Firefox - not Chrome. If I set it to HTTPS it works on Chrome and IE - Not Firefox. Same error:
"ReferenceError: FrameManager is not defined".
What is going on here?
a couple of things:
I would bet on a race condition when you have two independent
resources which are supposed to be loaded concurrently. You can
easily check this by writing to log (or to document, whichever works
for you) when both finish loading (i.e. add a little script in the
iframe to dynamically add the time to the content or write to log if
you're using chrome, do that in the external script file as well,
and see if they post the time in a specific order when this fails). In your case, if the script appears before the iframe, and you don't mark it as async, it should be loaded before the iframe is fetched, so it would seem strange for the iframe not to find it due to a race condition. I would bet on (3) in that case.
Assuming there is such an issue (and if there isn't now, when you go
out into the real world it will be), a better way to do this is to
make sure both behave well in case the other loads first. In your
case, I would tell the iframe to add itself to a local variable
independent of the script, and would tell the script to check if the
iframe registered when it loads, and after that in recurring
intervals until it finds the iframe.
If the page the script is loaded into is not in the same domain
as the iframe (note that it doesn't matter where the script comes
from, it only matters what the page's domain is), (or even the same
protocol as someone mentioned here), you will not be able to access
the content so you won't be able to resize according to what the
content is. I'm not sure about the onload method, if it's considered part of the wrapping page or part of the internal iframe.
Check out this question, it sounds relevant to your case:
There's also an interesting article here about this.
I think that your frame is loaded before the script, so "FrameManager" does not exist yet when the iframe has finished loading.
I'm trying to set up a website that loads pages through ajax calls replacing the current contents of with the ajax response. I'm putting a # and a page name at the end of my URLs so that people can book mark pages.
www.examplesite.com#home
www.examplesite.com#examples
www.examplesite.com#examples/example1
www.examplesite.com#examples/example2
I'm new to jQuery and to a lesser extent JavaScript but I'm trying to get a different page animation when I go to a page that is stored in a sub folder. fadeIn() works fine on both pages and pages in sub-folders however I can't get .slideDown() or .animate() to work at all. Here is an extract from my code:
<script>
//All pages are stored in a folder called 'pages' or a subfolder of 'pages'
$(document).ready(function(){
var myUrl = $(location).attr('href');
var noPage = myUrl.indexOf('#');
if(noPage == -1) {
location.hash = 'home';
}
window.onhashchange = function() {
pageChange();
}
function pageChange() {
var myUrl = $(location).attr('href');
var page = myUrl.substring(myUrl.indexOf('#') + 1, myUrl.length);
$.get('pages/' + page + '.html', function(pageHtml) {
if (page.indexOf('/') != -1) {
$('.main').hide().html(pageHtml).slideDown(400);
} else {
$('.main').hide().html(pageHtml).fadeIn(400);
}
});
};
pageChange();
});
</script>
If I'm approaching this from completely the wrong direction and that's why it's not working do feel free to point me in the correct direction by giving me an example of how it should work.
Got it!
I was using the css min-height property with a couple of my divs so that the page would expand automatically with the content if there was a lot on the page. If I remove the min-height property and replace it with a fixed height .slideDown() works fine.
Here are some links for more info if anyone else has the same issue:
http://www.only10types.com/2011/09/jquery-slidedown-doesnt-work-on.html
http://docs.jquery.com/Tutorials:Getting_Around_The_Minimum_Height_Glitch
I would take this...
if (page.indexOf('/') != -1) {
$('.main').hide().html(pageHtml).slideDown(400);
} else {
$('.main').hide().html(pageHtml).fadeIn(400);
}
And rearrange it to make sure your if statement is correct
if (page.indexOf('/') != -1) {
$('.main').hide().html(pageHtml).fadeIn(400);
} else {
$('.main').hide().html(pageHtml).slideDown(400);
}
If it now slides instead of fades, the if statement is corrupt
What about this ? Does this work ?
var main_div=$('.main');
main_div.hide();
$.get('pages/' + page + '.html', function(pageHtml) {
if (page.indexOf('/') != -1) {
main_div.html(pageHtml)
} else {
main_div.html(pageHtml)
}
});
main_div.slideDown(400);
maybe something in the CSS must be blocking it ? try disabling the CSS for the main class and try again ?
So,
I'm trying to come up with a way to dynamically load content into multiple tabs, where each tab can contain anywhere from one to several elements (reports).
Currently, the reports are loaded on page load with jQuery $.load. I'm using Bootstrap and bootstrap tabs. I found a site that teaches how to load multiple tabs, but not specifically what I need to do. That site is here: http://www.mightywebdeveloper.com/coding/bootstrap-2-tabs-jquery-load-content/
In contrast, each tab is set up more like this:
<div id="tab1">
<div id="report1"></div>
<div id="report2"></div>
</div>
I cannot use the top-level div to load the content, because it will potentially have multiple children. I need to loop through the div's, use regex to parse the ID, and load each report when the tabs are changed.
I haven't yet figured out the regex expression, but it should be fairly simple - the element id will be something like this : "#be78f5aa3-25". This is an alphanumeric 9-character dbid, followed by a hypen, followed by a 1-3 digit integer (not starting in 0). Then I need to split those two strings into separate variables and inject them into an API call.
Anyone looking to load multiple pages into bootstrap tabs may find this of use. I was able to get it working using some regex (specific to my application), placing div's within the tab-pane container's that had an Element Id which could be used to create the report I wanted to load into the container using $.load. I also added a few things for persistent tabs when the user went to another page and then used the back button, and another condition to load the content in the first tab if there was no hash in the URL.
I'm sure it could be cleaned up, but you get the gist..
$(function() {
"use strict";
var baseURL, $navbox;
baseURL = window.location.protocol + "//" + window.location.hostname + "/db/";
$navbox = $("#myTabs");
$navbox.bind("show", function(e) {
var contentID, pattern, selectDiv;
pattern = /#(\Btab|tab\B)?(\Bdropdown|dropdown\B)?([1-9]{1}[0-9]*)/i;
contentID = e.target.toString().match(pattern)[0];
selectDiv = contentID + " > div";
return $(selectDiv).each(function() {
var parts = this.id.match(/(##enter regex here)/);
if (parts) {
$(this).load(baseURL + parts[0]);
return;
}
return $("#myTabs").tab();
});
});
if (window.location.hash) {
$('#myTabs').find('a[href="'+window.location.hash+'"]').tab('show');
}
else {
var elemID = "#"+$('[class^="tab-pane active"]').attr('id') + " > div";
$(elemID).each(function() {
var parts = this.id.match(/(##enter regex here)/);
$(this).load(baseURL + parts[0]);
return $("#myTabs").tab();
});
}
});
$('#myTabs a').click(function (e) {
e.preventDefault();
var bob = jQuery(this).attr("href");
bob = jQuery.trim(bob);
if(bob == "" || bob == "javascript:void(0)") {
return;
}
else {
window.location.hash = $(this).attr('href');
$(this).tab('show');
}
});