I tried to register an onClick-handler using jQuery, which functionality should be to change the query string in the URL and to launch a reload whilst I assign a new URL to window.location.href.
// sets a new URL with lang as query parameter indicating the language
setNewLang: function( lang ) {
var that = this;
// the url that shall be changed
var url = window.location.href;
// save possible other query parameters
var tokenizedUrl = url.split("&");
// first string in the array contains language query parameter
var tokenZero = tokenizedUrl[0].split("l=");
// set the new language query parameter in the first part of the url
tokenizedUrl[0] = tokenZero[0] + "l=" + lang;
// concatenate the splitted url
var retVal = tokenizedUrl[0];
for(i=1; i<tokenizedUrl.length; i++) {
retVal = retVal + "&" + tokenizedUrl[i];
}
console.log(retVal);
// reload page with new query parameter for language
window.location = retVal;
return false;
}
/* language selection for navbar-right*/
$("#navbarRightLanguageListEnglish").on("click", function() {
console.log("DBG-INFO"); /* even the log never appears */
that.setNewLang("en_US");
});
I tried it with firefox and it worked.
Is there a bug in chromium? Or is it a problem of scope or jQuery or ...?
If there is another solution available to change and reload the site, I would be glad to know it.
Thanks for your help.
Hey folks!
I've forgotten to post the HTML and to say that I'm using bootstrap too.
By the way, I found the bug by myself, but thank you for your help.
<!-- Language Selection -->
<div id="navbarTopLanguage" class="dropdown dd-top">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" >Language<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<li id="navbarTopLanguageListEnglish" role="presentation"><a role="menuitem" tabindex="-1" href="">English</a></li>
<li id="navbarTopLanguageListDeutsch" role="presentation"><a role="menuitem" tabindex="-1" href="">Deutsch</a></li>
</ul>
</div>
<!-- End of Language Selection -->
The "href"-attributes are empty and that was my fault. Chromium gives them are (wrong) value so that clicking it has not the wwanted effect.
I fixed it with changing the javascript.
// sets a new URL with lang as query parameter indicating the language
setNewLang: function( id, lang ) {
// selfie-pattern
var that = this;
// the url that shall be changed
var url = window.location.href;
// save possible other query parameters
var tokenizedUrl = url.split("&");
// first string in the array contains language query parameter
var tokenZero = tokenizedUrl[0].split("l=");
// set the new language query parameter in the first part of the url
tokenizedUrl[0] = tokenZero[0] + "l=" + lang;
// concatenate the splitted url
var retVal = tokenizedUrl[0];
for(i=1; i<tokenizedUrl.length; i++) {
retVal = retVal + "&" + tokenizedUrl[i];
}
console.log(retVal);
// reload page with new query parameter for language
$(id).attr("href",retVal);
}
The new function replaces the value of the specified "href"-attribute (parameter "id") with the new URL.
Thanks for your help.
Please try
window.location.href = retVal;
instead of
window.location = '...'
If you don't want previous URL to go to browser history, try
window.location.replace(retVal)
Hope this helps.
Related
I have this piece of code on a site that exports the contents of local storage to a file in JSON format.
For some reason it stopped working. I tested it in multiple browsers but it's all the same...
No errors get displayed, yet it doesn't export either.
The different variables seem fine, yet it just isn't exporting.
To be honest I have no clue how to do this differently so any help would be appreciated.
Thx
function exportHistory() {
console.log("started");
var _myArray = JSON.stringify(localStorage , null, 4); //indentation in json format, human readable
var vLink = document.getElementById('exportHistory'),
var vBlob = new Blob([_myArray], {type: "octet/stream"}),
vName = 'working_history_' + todayDate() + '.json',
vUrl = window.URL.createObjectURL(vBlob);
console.log(vLink);
vLink.setAttribute('href', vUrl);
vLink.setAttribute('download', vName );
console.log("finished");
}
<button class="btn btn-outline-secondary btn-sm" id="exportHistory" onclick="exportHistory()">Export History</button >
Here you need to add the download attribute to an anchor tag <a> rather than the clicking button itself. You need to create an anchor tag with display:none and programmatically click it to download the file. Here is an example. Notice the button only used to execute the function and href and download attributes are added to the <a> tag.
function exportHistory() {
console.log("started");
var _myArray = JSON.stringify(localStorage , null, 4); //indentation in json format, human readable
//Note: We use the anchor tag here instead button.
var vLink = document.getElementById('exportHistoryLink');
var vBlob = new Blob([_myArray], {type: "octet/stream"});
vName = 'working_history_' + todayDate() + '.json';
vUrl = window.URL.createObjectURL(vBlob);
console.log(vLink);
vLink.setAttribute('href', vUrl);
vLink.setAttribute('download', vName );
//Note: Programmatically click the link to download the file
vLink.click();
console.log("finished");
}
Now add an empty anchor tag to the DOM.
<button class="btn btn-outline-secondary btn-sm" id="exportHistory" onclick="exportHistory()">Export History</button >
<a id="exportHistoryLink" style="display: none;">Export</a>
I have 2 methods. displayBookmark and deleteBookmarks. Currently I have onclick event that executes my deleteBookmark() method and also executes this.displayBookmark(). Without binding "this" element i couldn't execute this.displayBookmark(). My question how to get url parameter to deleteBookmark method?
I can't make it work on codepen so I will include github link
${onclick = this.deleteBookmark.bind(this)}
displayBookmark(){
this.bookmarksResults.innerHTML = ``;
for (let index = 0; index < bookmarks.length; index++) {
let name = (bookmarks[index].siteName).charAt(0).toUpperCase() + bookmarks[index].siteName.slice(1);
let url = bookmarks[index].siteUrl;
elements.bookmarksResults.innerHTML +=
`
<ul>
<li><h2 ><a class = "bookmarkResults__title" href="${url}" target = "_blank">${name}</a></h2>
<a ${onclick = this.deleteBookmark.bind(this)} class = "button button__delete">Delete</a>
<a class = "button button__edit">Edit</a>
<a class = "button button__visit" href="${url}" target = "_blank">Visit</a>
</li>
</ul>
`
}
}
deleteBookmark(){
console.log(url);
this.displayBookmark();
}
Somebody already gave me a good solution but it didn't worked for me and as a result a guy deleted his comment. But he was right. Basically I needed to modify these lines.
${onclick = this.deleteBookmark.bind(this, url)}
deleteBookmark(url){
console.log(url);
this.displayBookmark();
}
The problem was that I saved empty url to local storage, and because of it I saw console.log(url) empty and I thought that it didn't worked. Turns out I needed to clean my local storage. Glad I solved it in the end.
So I have something like this
<li><a href="new/page">Something</li>
<li><a href="#">Something else</li>
I want to be able to click one of the items, and send the current URL with so I can get it in the new page. I cannot store the current URL in the session because I will be going to a different location that doesn't have the same session. This is why I think that I want to have some sort of POST data so I can just send the URL or location along with it. I would like to keep it an <a> tag because that is how the style is set.
Try: <a href="new/page?variable=data">. When you are ready to extract the variable on another page, you can use something like this:
var myData = getQueryVariable("variable");
if(myData){
console.log(myData);//to verify it
}
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("?");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
console.log('Query Variable ' + variable + ' not found');
}
HTTP GET solution from PHP:
<li><a href="new/page?from=<?php echo $PHP_SELF?>" Something</li>
Maybe you can also rely on info from the http-referer headline.
Any suggestions as to why this dynamic value will not report report in GA?
To start:
I have created a way to split the URL parameters up so that I can insert the value from the URL that I want into the Google Analytics event onclick tracking.
This is an example of my URL:
<http://www.example.org/sweden/se/stod-oss/gava/info/?view=DDM&price=118>
The price in the url is a dynamic amount.
This is how I successfully split the url up in the :
<script type="text/javascript">
var params = {};
if (location.search) {
var parts = location.search.substring(1).split('&');
for (var i = 0; i < parts.length; i++) {
var nv = parts[i].split('=');
if (!nv[0]) continue;
params[nv[0]] = nv[1] || true;
}
}
</script>
So that works correctly and when I insert params.price into the button submit it works fine wen placed in the category section, like so:
<button type="submit" onClick="_gaq.push(['SE._trackEvent', 'se_donationpages', 'submitinfo', params.price,, false])" class="btn btn-gp btn-gp-special">Next<i class="icon-arrow-right icon-white"></i></button>
Google Analytics registers this fine in the reports.
But, this is not where I want this. I would like the price value to be inserted in the value section, like so:
<button type="submit" onClick="_gaq.push(['SE._trackEvent', 'se_donationpages', 'submitinfo', 'payment',params.price, false])" class="btn btn-gp btn-gp-special">Nästa <i class="icon-arrow-right icon-white"></i></button>
So, when I do this one above, Google Analytics does not register the event at all.
I thought there might be a problem with the value being a string, so I converted the price parameter to a integer like so in the head:
<script type="text/javascript">
var params = {};
if (location.search) {
var parts = location.search.substring(1).split('&');
for (var i = 0; i < parts.length; i++) {
var nv = parts[i].split('=');
if (!nv[0]) continue;
params[nv[0]] = nv[1] || true;
}
}
var price_param = params.price;
var view_param = params.view;
var price_param_int = parseInt(price_param)
</script>
and inserted the variable into the button code like so:
<button type="submit" onClick="_gaq.push(['SE._trackEvent', 'se_donationpages', 'submitinfo', 'payment',price_param_int, false])" class="btn btn-gp btn-gp-special">Next<i class="icon-arrow-right icon-white"></i></button>
...but, this doesnt report in GA :(
Any suggestions as to why this dynamic value will not report report in GA?
It's boggling my mind!
You are right that it must be an integer variable type. I don't know why GA doesn't just convert it automatically..
perhaps you simply typoed while posting, but in your code, you assign the integer-converted value to price_param_int (notice the lack of "s" on "param") but in your GA code you reference price_params_int
edit
Okay you mentioned in comment that it was just a typo when posting.. well I tested your code and it works fine. So here's another dumb question: are you sure you are going to your page with the price parameter actually in the URL? e.g.
http://www.yoursite.com/page.html?price=123
If you are and it's still not working then.. you must have something else going on that's affecting your code, because when I just have on a test page GA code and that button and the query param grabbing code you posted, it works fine.
If I write code in the JavaScript console of Chrome, I can retrieve the whole HTML source code by entering:
var a = document.body.InnerHTML; alert(a);
For fb_dtsg on Facebook, I can easily extract it by writing:
var fb_dtsg = document.getElementsByName('fb_dtsg')[0].value;
Now, I am trying to extract the code "h=AfJSxEzzdTSrz-pS" from the Facebook Page. The h value is especially useful for Facebook reporting.
How can I get the h value for reporting? I don't know what the h value is; the h value is totally different when you communicate with different users. Without that h correct value, you can not report. Actually, the h value is AfXXXXXXXXXXX (11 character values after 'Af'), that is what I know.
Do you have any ideas for getting the value or any function to generate on Facebook page.
The Facebook Source snippet is below, you can view source on facebook profile, and search h=Af, you will get the value:
<code class="hidden_elem" id="ukftg4w44">
<!-- <div class="mtm mlm">
...
....
<span class="itemLabel fsm">Unfriend...</span></a></li>
<li class="uiMenuItem" data-label="Report/Block...">
<a class="itemAnchor" role="menuitem" tabindex="-1" href="/ajax/report/social.php?content_type=0&cid=1352686914&rid=1352686914&ref=http%3A%2F%2Fwww.facebook.com%2 F%3Fq&h=AfjSxEzzdTSrz-pS&from_gear=timeline" rel="dialog">
<span class="itemLabel fsm">Report/Block...</span></a></li></ul></div>
...
....
</div> -->
</code>
Please guide me. How can extract the value exactly?
I tried with following code, but the comment block prevent me to extract the code. How can extract the value which is inside comment block?
var a = document.getElementsByClassName('hidden_elem')[3].innerHTML;alert(a);
Here's my first attempt, assuming you aren't afraid of a little jQuery:
// http://stackoverflow.com/a/5158301/74757
function getParameterByName(name, path) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(path);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var html = $('.hidden_elem')[0].innerHTML.replace('<!--', '').replace('-->', '');
var href = $(html).find('.itemAnchor').attr('href');
var fbId = getParameterByName('h', href); // fbId = AfjSxEzzdTSrz-pS
Working Demo
EDIT: A way without jQuery:
// http://stackoverflow.com/a/5158301/74757
function getParameterByName(name, path) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(path);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var hiddenElHtml = document.getElementsByClassName('hidden_elem')[0]
.innerHTML.replace('<!--', '').replace('-->', '');
var divObj = document.createElement('div');
divObj.innerHTML = hiddenElHtml;
var itemAnchor = divObj.getElementsByClassName('itemAnchor')[0];
var href = itemAnchor.getAttribute('href');
var fbId = getParameterByName('h', href);
Working Demo
I'd really like to offer a different solution for "uncommenting" the HTML, but I stink at regex :)