onclick: do something after changing location - javascript

Suppose I want to do the following: when clicking a 'div', change to another location (as if it was ...) and then do something. I have tried with this code:
<div onclick="location.reload();location.href='...';togglebox('#ident')">Title</div>
where ident is the identifier of an object in the new location href='...' and togglebox is a function defined in the script. But it seems that the browser tries to accomplish togglebox('#ident') before changing the location, so the output is not the expected one. For instance, if I try
<div onclick="location.reload();location.href='...';console.log(5)">Title</div>
then a 5 appears instantaneously before changing the location, while I expect the browser first changing the location and then showing 5.
Is there any solution to this reversal-order solution?
Any suggestion is welcome

One way would be to use a query string to tell the destination page what to do. However, if you want a hack that will do almost exactly what you ask, you can do this:
(This goes in your current page's click event handler)
window.location.href = '...'; // Go to another page in your site
localStorage.setItem('exec',"yourCodeInQuotes()");
Now the destination page should either be prepared to handle the ident you mentioned from localStorage or just evaluate the code directly. Either way you need the destination page to anticipate the data that's coming.
(This goes in the destination page)
var message = localStorage.getItem('exec'); // Will get whatever you stored
eval(message); // Will attempt to run it as JavaScript
$('#'+message); // Or find it if it was your ident and do stuff...

Related

Google Tag Manager Virtual Page View

I have a little problem setting up a virtualPageView which should override the URL which is sent to google when no result is present.
Heres what I have as JavaScript code:
function returnNoSearchResultsGoogleTagManagerCode($searchterm){
if ($searchterm == "") return "";
$requestUri = $_SERVER['REQUEST_URI'] . "&no_result=".$searchterm;
$js = "<script>
$(document).ready(function(){
dataLayer.push({
'event':'empty_result',
'virtualPageURL':'".$requestUri."'
});
});
</script>";
return $js;
}
As you can see, I want to use an event trigger (empty_result).
In google, I use a Trigger to determine if the Page is a no result Page. First i created a custom Variable with custom JS
function(){
if (document.getElementsByClassName('ga-no-result').length > 0){
return true;
}else{
return false
}
}
The class is set, if the SearchEngine can't find a result. So far so good.
I also created a dataLayer variable to hold the virtualPageURL
Now I need an event which is triggered if the variable is true.
Finally I created a Tag with type PageView which is fired when the event occurs:
Until now it seems okay, the Tag is properly configured (i guess) but if I do a search which has no result, the Page URL is not overridden
The Tag is properly fired and the variables are filled. The overview of the dataLayer shows a correct dataLayer event.
But the PageURL is not overridden... Even if I wait a whole day, the category isn't sent to google.
What am I doing wrong?
I would be very thankful if someone would have an idea or even a solution :)
Thanks in advance
exa.byte
UPDATE:
Hey, I forgot to mention, that I want to use the new page variable as the string which google should use to determine the searchterm and the searchcategory
In Google Analytics I configuered the search as the "q" parameter and the "no_result" as the category.
Is it even possible to change the string which google will parse in the end?
To send a virtual pageview to Google Analytics, the field you need to change is page not {{Page Url}} , also the title field is often used.
That's really the only two things you need to do to send a simple virtual pageview.
Extra: I always start my pagepath with /virtual/ to be able to recognize which ones are virtual pageviews easily in GA
For virtual page view you have to change Field "page" - in your GTM-OnSearchEmptyResult you are changing "{{Page URL}}" - I don't think that's correct way to send virutal pageview. Also if you need to change hostname use Fieldname "hostname".
In preview mode you will not see Page URL changed in Variables Tab, you have to go to the actual GA tag that is fired and check it's values. You can either do this in GTM's preview tool or you can use standard developer tools - Network Tab and see what values are being sent to GA:
You can see "dl" parameter is the current page, if you set up virtual page you should also see parameter called "dp" this is going to be the new value of page in your GA.
If you want to setup virtual pageview you have to use page instead of {{Page URL}} in your fieldname and for Document title use title in you fieldname.
for more field reference of google analytics follow below link
https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#hitType.
If you don't want to mess around with custom Tag Manager events it's still possible to use the good old ga method, even if you don't include the Analytics code on the page. You just need to fetch the right tracker dynamically, as explained by Simo Ahava in this thread.
if (typeof ga === "function") {
ga.getAll().forEach((tracker) => {
tracker.set('page', '/my/path'); // <- change here
tracker.send('pageview');
});
}
I also put it in a gist here.
thanks for your help. I think I got rid of the Problem and have solved it now. I will describe my solution below:
The solution is quite simple.
I had an error/ spelling error # google backend. I set the search_category parameter to "no_results", but used "no_result" for implementation...
Pretty dumb, but sometimes you just won't see the wood for the trees...
I created a new Trigger as helper "HelperDomReady" to trigger the only if DOM is ready and the variable "isEmptySearch" equals "(bool)true"
Now I can see the searchterms which have no result in google backend in the "sitesearch categories" summary. Since I won't set the parameter at all, if the search had at least one hit, the site-search category shows "not-set" for successful results. Therfore the category-section will only show searches without a hit. Problem solved :)
Disadvantage: The searchterm is also listed in the normal list. But I think this is negligible

Find all class and id names in an Ace Editor HTML script

What I'm trying to do:
Collect all the class and id names in an Ace Editor html script.
Right now my plan is to detect user changes (.on('change'...)) and get the current token using the cursor position. If the token is a not 'unquoted' 'attribute-value' type, I want to iterate back through previous tokens in order to find the 'attribute-name' type token to which that 'attribute-value' belongs and identify whether it is a class or id (I can't just detect the creation of an 'attribute-name' token because the user can go back and change the attribute-values later without changing the name, and I need to detect those changes).
I can do everything except for get previous tokens. I looked up some documentation and the TokenIterator is supposed to be able to do that, but when I try to do something like var iter = new TokeIterator(), my console says that TokenIterator is undefined. I've searched google over and over, but found no results. If the truth is out there I'm obviously not using the right words to find it, but they're the only words I've got.
Is some way built into Ace to iterate through tokens? I know I'm not seeing all the properties and methods on the editor instance object when I console log it, because I can use methods in my script that I can't see in that log. Is there one there that does what I want?
If not, how do I load the TokenIterator? I think something similar went on when I tried to use SnippetManager a while back and it turned out I actually had to do this to make it work:
var tillPageLoaded = setInterval(function() { // Makes sure page doesn't load forever on startup
if( document.readyState === 'complete') {
clearInterval(tillPageLoaded);
ace.config.loadModule('ace/ext/language_tools', function () {
editor.insertSnippet( myString );
});
}
}, 5);
Is this the same kind of situation? If so, what needs to be in .loadModules(...)? Do I need to reference a script somewhere? Does it need to be loaded some other way?
Is there built in functionality for Ace that would already do everything I want?
Other than that, if anyone has any better ideas of how to go about this with Ace, those would be very welcome.
you can get TokenIterator by using
var TokenIterator = ace.require("ace/token_iterator").TokenIterator
see https://github.com/ajaxorg/ace/blob/master/lib/ace/mode/folding/xml.js#L38 for an example of its usage.

Unable to set selected attribute after page loads

My html page with SELECT and OPTIONS values sets one of the options as a default.
Were the user to choose a different option, which then takes him to a new page, I’d like to preserve that value so the next time home page is generated the value the user selected should remain on display, rather than the original default value, when the window reloads.
How do I do this in javascript?
I had tried to save values via a DOM capture of the selected value, but I don’t seem to be able to change that original default value.
E.g.,, one line of code reads:
window.location.reload();
yet were I to use “hold values” to capture the user’s selected option that differs from the default option, like so:
var holdPick = document.getElementById(“uPick”).value;
window.location.reload();
document.getElementById(“uPick”).value = holdPick;
that won’t do the trick, and I know not why.
When you reload a page, all the JavaScript is reloaded too. So, that's why the JavaScript snippet you posted doesn't seem to be working... The line after window.location.reload(); isn't even run at all. If you want to have a value that persists between page loads, you'll need to set and retrieve a cookie. Check out the JavaScript document.cookie API at MDN. That should tell you what you need to know about storing and retrieving your value in a cookie.
Why: every time var holdPick is executed it will create variable from scratch.
Second line tells the browser to reload page, so the third line never gets the chance to be executed.
I'd recommend usage of HTML5 Web Storage
if (sessionStorage.uPick) { //check if variable has been set already
document.getElementById(“uPick”).value = sessionStorage.uPick;
} else {
sessionStorage.clickcount = document.getElementById(“uPick”).value;
}
you can use cookies also, but I don't think it is as straight forward.

Send variable value from page to another page

In my case :
I have created a form and in the form there is a button and a combo box that contains the data (Say it page A). When I click on the button, all I wanted was to call page B to perform a second process. The syntax for calling the page B is :
bb.pushScreen('PageB.htm', 'PageB', {'Key': MyComboValue});
How do I after page after page B called B will capture and get the value of the "MyComboValue" being sent from page A ??
Regards,
Bertho
Firstly, this is available in bbUI 0.94 (next branch) just to make sure you're running the right build.
Now, the object you pass to the new page is available in the ondomready, and onscreenready functions, so you would do something like this:
onscreenready: function(element, id, passed_object) { }
There are several ways to achieve this:
Use cookies to save the data. Wouldn't recommend it much.
Use localStorage. Works for newer browsers, some browsers won't be able to enjoy it.
Pass the values as querystring parameters when doing the change of url.
I would go with the third option myself. If you're only using JavaScript and you're not using any server side programming language:
Attach an event to the button so that when clicked, it fetches the data and generates a querystring. Then: top.location = "http://something/PageB.htm?" + querystring;
On the Page B, read the querystring (top.location.href) and parse it to get the querystring. Use the values of the querystring to set whatever you want on your page.
If you require code or if I misunderstood, please tell and I will check right away!
EDIT: I just realized you tagged your question as using blackberry-webworks. I have never worked with it and thus I have no idea if my solutions make sense on it. Try to specify it on your question too if possible, or in the title :)

Change the URL in the browser without loading the new page using JavaScript

How would I have a JavaScript action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark, then the new URL is used?
It would also be nice if the back button would reload the original URL.
I am trying to record JavaScript state in the URL.
If you want it to work in browsers that don't support history.pushState and history.popState yet, the "old" way is to set the fragment identifier, which won't cause a page reload.
The basic idea is to set the window.location.hash property to a value that contains whatever state information you need, then either use the window.onhashchange event, or for older browsers that don't support onhashchange (IE < 8, Firefox < 3.6), periodically check to see if the hash has changed (using setInterval for example) and update the page. You will also need to check the hash value on page load to set up the initial content.
If you're using jQuery there's a hashchange plugin that will use whichever method the browser supports. I'm sure there are plugins for other libraries as well.
One thing to be careful of is colliding with ids on the page, because the browser will scroll to any element with a matching id.
With HTML 5, use the history.pushState function. As an example:
<script type="text/javascript">
var stateObj = { foo: "bar" };
function change_my_url()
{
history.pushState(stateObj, "page 2", "bar.html");
}
var link = document.getElementById('click');
link.addEventListener('click', change_my_url, false);
</script>
and a href:
<a href="#" id='click'>Click to change url to bar.html</a>
If you want to change the URL without adding an entry to the back button list, use history.replaceState instead.
window.location.href contains the current URL. You can read from it, you can append to it, and you can replace it, which may cause a page reload.
If, as it sounds like, you want to record javascript state in the URL so it can be bookmarked, without reloading the page, append it to the current URL after a # and have a piece of javascript triggered by the onload event parse the current URL to see if it contains saved state.
If you use a ? instead of a #, you will force a reload of the page, but since you will parse the saved state on load this may not actually be a problem; and this will make the forward and back buttons work correctly as well.
I would strongly suspect this is not possible, because it would be an incredible security problem if it were. For example, I could make a page which looked like a bank login page, and make the URL in the address bar look just like the real bank!
Perhaps if you explain why you want to do this, folks might be able to suggest alternative approaches...
[Edit in 2011: Since I wrote this answer in 2008, more info has come to light regarding an HTML5 technique that allows the URL to be modified as long as it is from the same origin]
jQuery has a great plugin for changing browsers' URL, called jQuery-pusher.
JavaScript pushState and jQuery could be used together, like:
history.pushState(null, null, $(this).attr('href'));
Example:
$('a').click(function (event) {
// Prevent default click action
event.preventDefault();
// Detect if pushState is available
if(history.pushState) {
history.pushState(null, null, $(this).attr('href'));
}
return false;
});
Using only JavaScript history.pushState(), which changes the referrer, that gets used in the HTTP header for XMLHttpRequest objects created after you change the state.
Example:
window.history.pushState("object", "Your New Title", "/new-url");
The pushState() method:
pushState() takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL. Let's examine each of these three parameters in more detail:
state object — The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object.
The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts her browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage.
title — Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving.
URL — The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts her browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL.
Browser security settings prevent people from modifying the displayed url directly. You could imagine the phishing vulnerabilities that would cause.
Only reliable way to change the url without changing pages is to use an internal link or hash. e.g.: http://site.com/page.html becomes http://site.com/page.html#item1 . This technique is often used in hijax(AJAX + preserve history).
When doing this I'll often just use links for the actions with the hash as the href, then add click events with jquery that use the requested hash to determine and delegate the action.
I hope that sets you on the right path.
There is a Yahoo YUI component (Browser History Manager) which can handle this: http://developer.yahoo.com/yui/history/
Facebook's photo gallery does this using a #hash in the URL. Here are some example URLs:
Before clicking 'next':
/photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507
After clicking 'next':
/photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507#!/photo.php?fbid=496435457507&set=a.218088072507.133423.681812507&pid=5887085&id=681812507
Note the hash-bang (#!) immediately followed by the new URL.
A more simple answer i present,
window.history.pushState(null, null, "/abc")
this will add /abc after the domain name in the browser URL. Just copy this code and paste it in the browser console and see the URL changing to "https://stackoverflow.com/abc"
There's a jquery plugin http://www.asual.com/jquery/address/
I think this is what you need.
What is working for me is - history.replaceState() function which is as follows -
history.replaceState(data,"Title of page"[,'url-of-the-page']);
This will not reload page, you can make use of it with event of javascript
I was wondering if it will posible as long as the parent path in the page is same, only something new is appended to it.
So like let's say the user is at the page: http://domain.com/site/page.html
Then the browser can let me do location.append = new.html
and the page becomes: http://domain.com/site/page.htmlnew.html and the browser does not change it.
Or just allow the person to change get parameter, so let's location.get = me=1&page=1.
So original page becomes http://domain.com/site/page.html?me=1&page=1 and it does not refresh.
The problem with # is that the data is not cached (at least I don't think so) when hash is changed. So it is like each time a new page is being loaded, whereas back- and forward buttons in a non-Ajax page are able to cache data and do not spend time on re-loading the data.
From what I saw, the Yahoo history thing already loads all of the data at once. It does not seem to be doing any Ajax requests. So when a div is used to handle different method overtime, that data is not stored for each history state.
my code is:
//change address bar
function setLocation(curLoc){
try {
history.pushState(null, null, curLoc);
return false;
} catch(e) {}
location.hash = '#' + curLoc;
}
and action:
setLocation('http://example.com/your-url-here');
and example
$(document).ready(function(){
$('nav li a').on('click', function(){
if($(this).hasClass('active')) {
} else {
setLocation($(this).attr('href'));
}
return false;
});
});
That's all :)
I've had success with:
location.hash="myValue";
It just adds #myValue to the current URL. If you need to trigger an event on page Load, you can use the same location.hash to check for the relevant value. Just remember to remove the # from the value returned by location.hash e.g.
var articleId = window.location.hash.replace("#","");

Categories

Resources