I'm working on a project where I need to switch the base layer, according to the user preferences with the inicial zoom (already working). I don't really know where, but i've seen that by default, the base layer "Google Satellite" is the one selected. I've tried to do by triggering a click on the wanted radio button and, the radio button get clicked visually, but nothing happend (the map selected is always "Satellite", no matter if I triggered a click or I don't know). I have tried SO MANY THINGS but this is like wet soap in my hands... when I think i have got the right way, it slides away
function zoominicial(){
$.getJSON('servicos/usuario.svc/getZoomInicial', function (data) {
var ret = data.d;
var bsNum;
if (ret != "ERRO")
{
if(!ret){
zoomtoextent();
}
else
{
var base_Layer = ret.split(';')[1];
var extentUsuario = ret.split(';')[0].split(',');
var bsType;
switch(base_Layer){
case "Google Satellite":
$(".baseLayersDiv input")[0].click();
$(".baseLayersDiv input")[0].checked = true;
bsNum = 0;
bsType = "satellite";
checkRadio();
break;
case "Google Hybrid":
$(".baseLayersDiv input")[1].click();
$(".baseLayersDiv input")[1].checked = true;
bsNum = 1;
bsType = "hybrid";
checkRadio();
break;
case "Google Street Maps":
$(".baseLayersDiv input")[2].click();
$(".baseLayersDiv input")[2].checked = true;
bsNum = 2;
bsType = "roadmap";
checkRadio();
break;
case "Sem Foto":
$(".baseLayersDiv input")[3].click();
$(".baseLayersDiv input")[3].checked = true;
bsNum = 3;
checkRadio();
break;
}
function checkRadio(){
var radioBs = $('input:radio[name="' + map.layers[bsNum].name + '"]');
if(radioBs.is(':checked') === false) {
radioBs.filter('[value=' + map.layers[bsNum].value + ']').prop('checked', true);
}
}
if (map.baseLayers == undefined || map.baseLayers == "")
map.layers[bsNum].type = bsType;
else
map.baseLayers.type = bsType;
map.zoomToExtent(extentUsuario,map.layers[bsNum].projection);
$(".baseLayersDiv input").on("click", function(){
$(".baseLayersDiv input")[bsNum].checked= true;
});
$(""+map.layers[bsNum].id+"").trigger( "select" );
var linkEl = $('label[for="'+""+ $(".baseLayersDiv input")[bsNum].id +""+'"]');
if ( linkEl.click() === undefined ) {
document.location = linkEl.attr ( 'index.aspx' );
}
else {
linkEl.click();
$(".baseLayersDiv input")[bsNum].click();
}
}
}
else {
$.messager.alert('cGIS', 'Não foi possível exibir o zoom inicial.');
}
setTimeout(2000);
});
}
You see... I have tried every way to make the selection of the base layer but with no success.
I just can't reach the attributes of determinated base layer, because the children of the array of radio buttons are encapsulated. Does someone knows how to do it, PLEASE? I'm about to get crazy and throw my desk through the window!
You have to find where all of the layers are defined or know where the instances are stored and call function setVisible(false) to all of them except the one you would like to have active on the begening. Changing unbined radio buttons wont change anything. Better would be to initialize them with the corresponding value to "visible" parameter. All layers are visible by deafault, and in case of full raster layers you will see only the top one.
OL - setVisible API
Related
I am trying to build a menu which detects hover states and hide/shows relevant divs depending on where the mouse is. I need to do this with Prototype.js.
The menu looks something like this :
========ONE========TWO======THREE=======FOUR======FIVE======
============================================================
------------------- BIG MIDDLE DIV -------------------------
============================================================
============================================================
-------------------- TARGET HIDDEN DIV ---------------------
============================================================
When you mouse over link one,two,three.. it will show the related target div. The trick is when you mouseout, it needs to keep that div visible if you are on the middle div or the active state div. If you mouseout anywhere else in the body it needs to hide. Here is updated code based off the answer so far.
<ul><li #id="one">one</li><li>two</li><li>three</li><li>four</li></ul>
<div id="middleBar"></div>
<div id="container-one">1</div>
<div id="container-two">2</div>
<div id="container-three">3</div>
<div id="container-four">4</div>
<script>
MouseOff = true;
function getTarget(event) {
var el = event.target || event.srcElement;
return el.nodeType == 1? el : el.parentNode;
}
var ShowDiv = function(activeDiv){
$(activeDiv).addClassName('isActive');
var activeSibs = $(activeDiv).siblings();
activeSibs.invoke('removeClassName', 'isActive');
};
var HideDiv = function(){
if(MouseOff){
$$('div').invoke('removeClassName','isActive');
}
};
$$('li').invoke('observe','mouseenter',function(){
console.log(getTarget(event));
MouseOff = false;
var linkName = this.innerHTML;
var activeDiv = 'container-' + linkName;
ShowDiv(activeDiv);
});
$$('li').invoke('observe','mouseleave',function(){
MouseOff = true;
HideDiv();
});
$$('#middleBar').invoke('observe','mouseenter',function(){
console.log(getTarget(event));
MouseOff = false;
});
</script>
Here is a fiddle of this :
http://jsfiddle.net/TqMtK/5/
To further clarify what I am trying to achieve, once the div is activated it needs to stay visible while on that nav trigger, the middle bar, or the active div itself. Something else I was thinking was to use that getTarget function to always check what element the mouse is above, but this just feels wrong to me and does not seem very efficient. Any opinions on that?
UPDATE : Still trying to work through this.. now I am a little closer and the flag is set correctly when over middle div, but when it goes over the active div it resets the flag and the div disappears. I tried adding back a timeout.. here is latest attempt :
http://jsfiddle.net/TqMtK/7/
UPDATE : Ok I think I might have this, at this point I would like to just hear any feedback on this solution. I found that because the active class is being added dynamically the observer method must be included in the function that creates it : ShowDiv. Here is what I got :
http://jsfiddle.net/TqMtK/9/
UPDATED: tues night. I am sure this can be more succinct. Perhaps it is just my browser but I notice that I can only mouse over Panel1 and show that it doesn't disappear, the other Panels (because of their positioning) leave a space which is the "body" and I close on that. Hopefully this is a bit better.
http://jsfiddle.net/TqMtK/12/
var tabPanels = {
options : {
activePanel : "",
activeTab : ""
},
showPanel : function(panel){
this.hidePanel();
this.options.activePanel = 'container-' + panel;
this.options.activeTab = panel;
$(this.options.activePanel).addClassName('isActive').setAttribute('panel',panel);
},
hidePanel : function(panel){
if(Object.isElement($(panel)) && $(panel).hasAttribute('panel') ){
if($(panel).readAttribute('panel') == this.options.activeTab ){
return;
}else{
if(!this.options.activePanel.blank()){
$(this.options.activePanel).removeClassName('isActive');
}
}
}else{
if(!this.options.activePanel.blank()){
$(this.options.activePanel).removeClassName('isActive');
}
}
}
}
document.observe('mouseover', function(e){
switch(e.target.id){
case 'middleBar':
break;
case 'one':
case 'two':
case 'three':
case 'four':
tabPanels.showPanel(e.target.id);
break;
default:
tabPanels.hidePanel(e.target.id);
}
})
After much tinkering I finally found a working solution for this. Thanks to the idea from james I went the route of setting a flag depending on which element the mouse was over. That combined with a timeout allowed me to keep running checks on the mouse location. Part of my problem was where I was invoking the observe event on the class that was dynamically added from ShowDiv(), when I moved it in to that function I was able to get it to work. Here is the js I ended up with
MouseLocator = 'off';
var ShowDiv = function(activeDiv){
$(activeDiv).addClassName('isActive');
var activeSibs = $(activeDiv).siblings();
activeSibs.invoke('removeClassName', 'isActive');
$$('.isActive').invoke('observe','mouseenter',function(){
MouseLocator = 'on';
});
$$('.isActive').invoke('observe','mouseleave',function(){
MouseLocator = 'off';
setTimeout(function(){HideDiv()},500);
});
};
var HideDiv = function(){
if(MouseLocator == 'off'){
$$('div').invoke('removeClassName','isActive');
}
};
$$('li').invoke('observe','mouseenter',function(){
MouseLocator = 'on';
var linkName = this.innerHTML;
var activeDiv = 'container-' + linkName;
ShowDiv(activeDiv);
});
$$('li').invoke('observe','mouseleave',function(){
MouseLocator = 'off';
setTimeout(function(){HideDiv()},500);
});
$$('#middleBar').invoke('observe','mouseenter',function(){
MouseLocator = 'on';
});
$$('#middleBar').invoke('observe','mouseleave',function(){
MouseLocator = 'off';
setTimeout(function(){HideDiv()},500);
});
and a fiddle : http://jsfiddle.net/TqMtK/9/
I guess this is resolved but I am always open to suggestions on how to improve my code :)
i have designed chess board using buttons.Initially all the values on the button will be null,upon loading the page all the pieces appear on them and the piece of code is as follows
<input type="button" id="A8" value="" style="background:#FFE4C4;font-size: 70px;height:90;width:100" onclick="check(this.id)">
and in the onLoad function,the ASCII charecter of the chess pieces are assigned as follows:
document.getElementById('A1').value=String.fromCharCode(9814);
Now what i want is to change the one piece from a button to another on clicking two buttons.i had tried a lot with the following script
function check(clicked_id) {
var Button_2 = "";
if (i < 2) {
i++;
// alert("i:"+i);
if (i == 1) {
Button_1 = clicked_id;
B1_val = document.getElementById(Button_1).value;
alert("B1 Button val:" + B1_val);
}
if (i == 2) {
var Button_2 = clicked_id;
B2_val = document.getElementById(Button_2).value;
alert("b1 val:" + B1_val);
alert("B2 val:" + B2_val);
B2_val = B1_val;
B1_val = "";
alert("B1 val:" + B1_val + "B2 val:" + B2_val);
}
} else {
alert("Only 2 butons should press..i:" + i);
i = 0;
}
// alert("clcked a button:"+clicked_id);
}
But the code is not working
If you just want to move the value from the location of the first click to the location of the second click, then you can do that fairly simply like this:
var lastClick;
function check(id) {
var src, dest;
if (!lastClick) {
// no previous click so just store the location of this first click
lastClick = id;
} else {
// move value from lastClick id to new id
src = document.getElementById(lastClick);
dest = document.getElementById(id);
dest.value = src.value;
src.value = "";
lastClick = null;
}
}
I assume that a real application would need all sorts of error handling that doesn't let you put a piece on top of another piece, ignores first clicks on empty spaces, enforces only legal moves, etc...
I'm using arbor.js to create a graph.
How do I create an onclick event for a node, or make a node link somewhere upon being clicked?
The Arborjs.org homepage has nodes which link to external pages upon being clicked, how do I replicate this, or make the node call javascript function upon being clicked?
My current node and edges listing is in this format:
var data = {
nodes:{
threadstarter:{'color':'red','shape':'dot','label':'Animals'},
reply1:{'color':'green','shape':'dot','label':'dog'},
reply2:{'color':'blue','shape':'dot','label':'cat'}
},
edges:{
threadstarter:{ reply1:{}, reply2:{} }
}
};
sys.graft(data);
A bit of context:
I'm using arbor.js to create a graph of thread starters and replies on my forum.
I've got it working so that id's are displayed 'in orbit' around their respective thread starter.
The reference on the arbor site is really not very helpful.
Any help is much appreciated.
If you look at the atlas demo code (in github) you will see towards the bottom there are a selection of mouse event functions, if you look at:
$(canvas).mousedown(function(e){
var pos = $(this).offset();
var p = {x:e.pageX-pos.left, y:e.pageY-pos.top}
selected = nearest = dragged = particleSystem.nearest(p);
if (selected.node !== null){
// dragged.node.tempMass = 10000
dragged.node.fixed = true;
}
return false;
});
This is being used to control the default node "dragging" functionality. In here you can trigger the link you want.
I would add the link URL to the node json that you are passing back to define each node, so your original JSON posted becomes something like:
nodes:{
threadstarter:{'color':'red','shape':'dot','label':'Animals'},
reply1:{'color':'green','shape':'dot','label':'dog', link:'http://stackoverflow.com'},
reply2:{'color':'blue','shape':'dot','label':'cat', link:'http://stackoverflow.com'}
},
Then, you can update the mouseDown method to trigger the link (the current node in the mouse down method is "selected" so you can pull out the link like selected.node.data.link
If you look at the original source for the arbor site to see how they have done it, they have a clicked function that is called on mouseDown event and then essentially does:
$(that).trigger({type:"navigate", path:selected.node.data.link})
(edited for your purposes)
It is worth noting that whilst the Arbor framework and demos are open for use, their site isnt and is actually copyrighted, so only read that to see how they have done it, dont copy it ;)
With the above solutions (including the one implemented at www.arborjs.org) although nodes can open links when clicked, they also lose their ability to be dragged.
Based on a this question, that discusses how to distinguish between dragging and clicking events in JS, I wrote the following:
initMouseHandling:function(){
// no-nonsense drag and drop (thanks springy.js)
selected = null;
nearest = null;
var dragged = null;
var oldmass = 1
var mouse_is_down = false;
var mouse_is_moving = false
// set up a handler object that will initially listen for mousedowns then
// for moves and mouseups while dragging
var handler = {
mousemove:function(e){
if(!mouse_is_down){
var pos = $(canvas).offset();
_mouseP = arbor.Point(e.pageX-pos.left, e.pageY-pos.top)
nearest = particleSystem.nearest(_mouseP);
if (!nearest.node) return false
selected = (nearest.distance < 50) ? nearest : null
if(selected && selected.node.data.link){
dom.addClass('linkable')
} else {
dom.removeClass('linkable')
}
}
return false
},
clicked:function(e){
var pos = $(canvas).offset();
_mouseP = arbor.Point(e.pageX-pos.left, e.pageY-pos.top)
nearest = particleSystem.nearest(_mouseP);
if (!nearest.node) return false
selected = (nearest.distance < 50) ? nearest : null
if (nearest && selected && nearest.node===selected.node){
var link = selected.node.data.link
if (link.match(/^#/)){
$(that).trigger({type:"navigate", path:link.substr(1)})
}else{
window.open(link, "_blank")
}
return false
}
},
mousedown:function(e){
var pos = $(canvas).offset();
_mouseP = arbor.Point(e.pageX-pos.left, e.pageY-pos.top)
selected = nearest = dragged = particleSystem.nearest(_mouseP);
if (dragged.node !== null) dragged.node.fixed = true
mouse_is_down = true
mouse_is_moving = false
$(canvas).bind('mousemove', handler.dragged)
$(window).bind('mouseup', handler.dropped)
return false
},
dragged:function(e){
var old_nearest = nearest && nearest.node._id
var pos = $(canvas).offset();
var s = arbor.Point(e.pageX-pos.left, e.pageY-pos.top)
mouse_is_moving = true
if (!nearest) return
if (dragged !== null && dragged.node !== null){
var p = particleSystem.fromScreen(s)
dragged.node.p = p
}
return false
},
dropped:function(e){
if (dragged===null || dragged.node===undefined) return
if (dragged.node !== null) dragged.node.fixed = false
dragged.node.tempMass = 50
dragged = null
selected = null
$(canvas).unbind('mousemove', handler.dragged)
$(window).unbind('mouseup', handler.dropped)
_mouseP = null
if(mouse_is_moving){
// console.log("was_dragged")
} else {
handler.clicked(e)
}
mouse_is_down = false
return false
}
}
$(canvas).mousedown(handler.mousedown);
$(canvas).mousemove(handler.mousemove);
}
}
As you can see,
I made a difference between the clicked and mousedown handler functions.
I am opening links in new tabs. To simply redirect, change:
window.open(link, "_blank") for window.location = link.
The above must replace your previous initMouseHandling function in the renderer.js file.
Define "dom" as: var dom = $(canvas)
You have to add the following css code to give feedback to the user.
canvas.linkable{
cursor: pointer;
}
In the script renderer.js is the handler for the mouse events, so you can add your code to create your functions.
I modified the renderer.js to add the click and double-click functions.
var handler = {
clicked:function(e){
var pos = $(canvas).offset();
_mouseP = arbor.Point(e.pageX-pos.left, e.pageY-pos.top)
selected = nearest = dragged = particleSystem.nearest(_mouseP);
if (dragged.node !== null) dragged.node.fixed = true
$(canvas).bind('mousemove', handler.dragged)
$(window).bind('mouseup', handler.dropped)
$(canvas).bind('mouseup', handler.mypersonalfunction)
},
mypersonalfunction:function(e){
if (dragged===null || dragged.node===undefined) return
if (dragged.node !== null){
dragged.node.fixed = false
var id=dragged.node.name;
alert('Node selected: ' + id);
}
return false
},
You can check the clic and double-click functions in this page.
I add nodes and edges when a node has been clicked and I add edges to other nodes when the node has been double-clicked (the blue,yellow and green ones)
I´m looking for similar customization for selection over each node id value.
How would it be if instead of mouse-handler trigger, the selection was made via checkbox inside each node?
<input type=checkbox name=mycheckbox[]>
I am trying to build a site with keyboard navigation. I want the user to be able to navigate through a menu of five or six pages using the left and right arrows.
No matter on which page is the user, I want him/her to go back/forward in the menu when the left/right arrow is pressed.
Let's say the horizontal menu is built this way :
[Home / Random page / Some page / Another page / And so on]
Apparently it is not working. Here is what I have so far :
document.onkeyup = KeyCheck;
var pages = ["index.php", "random-page.php", "some-page.php", "another-page.php", "and-so-on.php"];
function leftarrowpressed() {
location.href = pages[0]-1;
}
function rightarrowpressed() {
location.href = pages[0]+1;
}
}
function KeyCheck(e)
{
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID)
{
// left arrow key
case 37:
leftarrowpressed()
break;
// right arrow key
case 39:
rightarrowpressed()
break;
}
}
Thank you all for your help.
pages[0]-1 will evaluate to "index.php"-1 which is NaN. You don't want to subtract 1 from the page URL (you basically cannot subtract from strings) - rather subtract 1 from the index to get the previous page. Also, guard for the bounds:
location.href = pages[ Math.max(0, 0 - 1) ];
and:
location.href = pages[ Math.min(pages.length - 1, 0 + 1) ];
I guess you replace the 0 with the index of the current page automatically.
Secondly, you have an extraneous } in rightarrowpressed it seems.
okay, I checked out your site and modified/extended my code slightly to try to (almost) achieve what it is I think you want to do. I'm going to leave the other answer unedited because it shows what is probably a better method for doing this... This solution is rather hack-y, and just a way to illustrate the concept.
To see it, go to any of your pages (except the blog page), then open up webkit inspector (my code will only work in WebKit(chrome/safari), although it would be REALLY easy to make it work in any browser) and enter the following into the javascript console:
document.querySelector("footer").setAttribute("style","position:fixed;bottom:0px;width:100%;");
document.querySelector("header").setAttribute("style","position:fixed;top:0px;width:100%;");
var pages = ["accueil","references","cv","contact","aide","blog"],
classNames = ["accueil","ref","cv","contact","aide","blog"],
pageUrls = ["","references.php","cv.php","contact.php","aide.php","blog/"]
baseUrl = "http://maximelaforet.com/",
currentPageIndex = pageUrls.indexOf(window.location.href.replace(baseUrl,"")),
pageDivs = [1,1,1,1,1,1];
pageDivs[currentPageIndex] = document.querySelector("div.content");
pageDivs[currentPageIndex].id = pages[currentPageIndex]+"Page";
pageDivs[currentPageIndex].setAttribute("style","-webkit-transition:all 1s ease-in-out;position:fixed;top:63px;width:100%;height:"+(window.innerHeight - 270)+"px;overflow:scroll;");
for (var i=0; i<pageUrls.length;i++)
{
if (i!=currentPageIndex)
{
var pageGrabber = new XMLHttpRequest();
pageGrabber.open("GET","http://maximelaforet.com/" + pageUrls[i], false);
pageGrabber.send(null);
if (pageGrabber.status==200)
{
var temp = document.createElement("div");
temp.innerHTML = pageGrabber.response;
if (pages[i]!="blog")
pageDivs[i] = temp.querySelector("div.content").cloneNode(true);
else
pageDivs[i] = temp.querySelector("div#page").cloneNode(true);
}
pageDivs[i].id = pages[i]+"Page";
pageDivs[i].setAttribute("style","-webkit-transition:-webkit-transform 1s ease-in-out;position:fixed;top:63px;width:100%;height:"+(window.innerHeight - 270)+"px;overflow:scroll;");
if (i<currentPageIndex)
pageDivs[i].style.webkitTransform = "translate3d(-100%,0,0)";
else
pageDivs[i].style.webkitTransform = "translate3d(100%,0,0)";
document.body.appendChild(pageDivs[i]);
}
}
window.addEventListener("keyup", KeyCheck, true);
function KeyCheck(e)
{
e.preventDefault();
e.stopPropagation();
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID)
{
// left arrow key
case 37:
if (currentPageIndex == 0)//we're at the first page, go to the last
currentPageIndex = pages.length - 1;//-1 to account for first index being "0"
else//go to the previous page
pageDivs[currentPageIndex].style.webkitTransform = "translate3d(100%,0,0)";
pageDivs[currentPageIndex-1].style.webkitTransform = "translate3d(0,0,0)";
document.querySelector("header").classList.remove(classNames[currentPageIndex]);
document.querySelector("header").classList.add(classNames[currentPageIndex-1]);
if (classNames[currentPageIndex] == "accueil")
document.querySelector("li > a[class~='"+classNames[currentPageIndex]+"']").classList.toggle("current_acc");
else
document.querySelector("li > a[class~='"+classNames[currentPageIndex]+"']").classList.toggle("current_"+classNames[currentPageIndex]);
if (classNames[currentPageIndex] == "accueil")
document.querySelector("li > a[class~='"+classNames[currentPageIndex-1]+"']").classList.toggle("current_acc");
else
document.querySelector("li > a[class~='"+classNames[currentPageIndex-1]+"']").classList.toggle("current_"+classNames[currentPageIndex-1]);
currentPageIndex--;
break;
// right arrow key
case 39:
if (currentPageIndex == (pages.length - 1))//if we're at the last page, go to the first
currentPageIndex = 0;
else//go to the next page
pageDivs[currentPageIndex].style.webkitTransform = "translate3d(-100%,0,0)";
pageDivs[currentPageIndex+1].style.webkitTransform = "translate3d(0,0,0)";
document.querySelector("header").classList.remove(classNames[currentPageIndex]);
document.querySelector("header").classList.add(classNames[currentPageIndex+1]);
if (classNames[currentPageIndex] == "accueil")
document.querySelector("li > a[class~='"+classNames[currentPageIndex]+"']").classList.toggle("current_acc");
else
document.querySelector("li > a[class~='"+classNames[currentPageIndex]+"']").classList.toggle("current_"+classNames[currentPageIndex]);
if (classNames[currentPageIndex] == "accueil")
document.querySelector("li > a[class~='"+classNames[currentPageIndex+1]+"']").classList.toggle("current_acc");
else
document.querySelector("li > a[class~='"+classNames[currentPageIndex+1]+"']").classList.toggle("current_"+classNames[currentPageIndex+1]);
currentPageIndex++;
break;
default:
var noChange = true;//just so we can ignore the rest if a boring key
}
}
Keep in mind, though, this is a really hack-y way to do it, but it should point you in the right direction. Let me know if you have more questions.
Well, seems to me you'll need to know which page you're currently on each time for it to work. For this I'd recommend window.localStorage if (and only if) A) all of the pages are served from the same domain, and B) You don't need to support older browsers. If either of those are untrue, this method won't work, and you'll need to do something else like parse the URL string.
I took your code and modified it slightly to show how you might use localStorage. I added some comments, but it should be relatively self-explanatory. Here 'tis:
//if current index don't exist, make it
if (!window.localStorage.currentPageIndex)
{
window.localStorage.currentPageIndex = 0;//frustratingly, it gets stringified anyway - you have to parseInt later
}
//set up vars
var pages = ["index.php", "random-page.php", "some-page.php", "another-page.php", "and-so-on.php"],
currentPageIndex = parseInt(window.localStorage.currentPageIndex);//as promised
//set event listener on window
window.addEventListener("keyup", KeyCheck);
function KeyCheck(e)
{
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID)
{
// left arrow key
case 37:
if (currentPageIndex == 0)//we're at the first page, go to the last
currentPageIndex = pages.length - 1;//-1 to account for first index being "0"
else//go to the previous page
currentPageIndex--;
break;
// right arrow key
case 39:
if (currentPageIndex == (pages.length - 1))//if we're at the last page, go to the first
currentPageIndex = 0;
else//go to the next page
currentPageIndex++;
break;
default:
var noChange = true;//just so we can ignore the rest if a boring key
}
if (!noChange)//haha, I love double negatives
{
//now dump the new current page index back into localStorage
window.localStorage.currentPageIndex = currentPageIndex;
//first, try it in your javascript console to make sure it works (refresh the page!)
console.log(pages[currentPageIndex],currentPageIndex);
//then use real urls and uncomment the next line to go to the new current page!
//location.href = pages[currentPageIndex]
}
}
But - I've gotta ask - do you really want to do it this way? that's a lot of HTTP requests and refreshing the page - are the pages small enough that you could just load them all together at once, and simply only display one at a time? (you could even do a cool sliding or crazy 3d effect between pages - again, assuming you only need to support newer browsers...)
Tampermonkey is an extension for Google Chrome that attempts to emulate the functionality of Greasemonkey. To be clear, I got my script to work in Chrome and the default JavaScript changes to show up. I wanted to test the menu commands, however, and entered a 6-digit hex color code after clicking on the command in the Tampermonkey menu. I reloaded the page, and the commands disappeared from the menu! My script was still there (and the checkbox was ticked).
No matter what I did or what code I changed, I could never emulate this initial functionality after that user-defined input was set. This leads me to believe that there's some persistent data that I can't delete that's causing my script to fail prematurely. NOTE: This exact script works perfectly and without errors in Firefox.
This is obviously not a Tampermonkey forum, but people here seem very knowledgeable about cross-platform compatility. I didn't hear a single peep from the Chrome console after all of the changes below, and I'm really just out of ideas at this point. Here are some things I've tried (with no success). Any console errors are listed:
Changing jQuery version from 1.5.1 to 1.3.2
Calling localStorage.getItem('prevoColor') from console after page load (both values null)
Changing client-side storage from localStorage to get/setValue
Calling GM_getValue from the console = ReferenceError: GM_getValue is not defined
Deleting localStorage entries for veekun.com in Chrome options
Refreshing, Re-installing the script, and restarting the browser more times than I can count
Repeating all of the above commands using Firebug Lite (bookmarklet)
Here's the code I was using:
// ==UserScript==
// #name Veekun Comparison Highlighter
// #namespace tag://veekun
// #description Highlights moves exclusive to pre-evolutions on veekun.com's family comparison pages (user-defined colors available)
// #include http://veekun.com/dex/gadgets/*
// #author Matthew Ammann
// #version 1.0.3
// #date 3/11/11
// #require http://sizzlemctwizzle.com/updater.php?id=98824
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==
/*
Goal: Change checkmark color & move name to user-specified color on family comparison pages if
[DONE] Baby poke has a LEVEL-UP move unlearned by any evolutions
[DONE] a) Make sure move is not a TM or tutor move
[DONE] Any other mid-evolution has a move unlearnable by a final evo (Caterpie, Weedle families)
[DONE] a) Make sure move is not a TM or tutor move
[DONE] Any pre-evo has a TUTOR move unlearned by any evo (Murkrow in HG/SS)
[] Implement auto-update after uploading to userscripts.org
Credits: Brock Adams, for helping with Chrome compatibility
Metalkid, for the jQuery consult
*/
var isLevelupMove = false;
var isTutorMove = false;
var isTM = false;
var TMhead = $('#moves\\:machine');
var hasSecondEvo = false;
var hasFinalEvo1 = false;
var hasFinalEvo2 = false;
var header = $('.header-row').eq(1);
var TMmoves = new Array();
//This section deals with the user-defined colors
GM_registerMenuCommand("Color for pre-evolutionary-only moves", prevoColorPrompt)
GM_registerMenuCommand("Color for first evolution-only moves", evoColorPrompt)
var prevoColor = GM_getValue('prevoColor', '#FF0000');
var evoColor = GM_getValue('evoColor', '#339900');
function prevoColorPrompt()
{
var input = prompt("Please enter a desired 6-digit hex color-code for pre-evolutionary pokemon:")
GM_setValue('prevoColor', '#'+input);
}
function evoColorPrompt()
{
var input = prompt("Please enter the desired 6-digit hex color-code for first-evolution pokemon:")
GM_setValue('evoColor', '#'+input);
}
//This loop tests each 'th' element in a sample header row, determining how many Evos are currently present in the chart.
$('.header-row').eq(1).find('th').each(function(index)
{
if($(this).find('a').length != 0)
{
switch(index)
{
case 2:
hasSecondEvo = true;
break;
case 3:
hasFinalEvo1 = true;
break;
case 4:
hasFinalEvo2 = true;
break;
}
}
});
//All 'tr' siblings are TM moves, since it's the last section on the page
//This array puts only the names of the available TMs into the TMmoves array
TMhead.nextAll().each(function(index)
{
TMmoves.push($(this).children(":first").find('a').eq(0).html());
});
$('tr').each(function(index)
{
var moveName = $(this).children(":first").find('a').eq(0).html();
moveName = $.trim(moveName);
switch($(this).attr('id'))
{
case 'moves:level-up':
isLevelupMove = true;
break;
case 'moves:egg':
isLevelupMove = false;
break;
case 'moves:tutor':
isTutorMove = true;
case 'moves:machine':
isTM = true;
}
if(isLevelupMove || isTutorMove)
{
var babyMoveCell = $(this).find('td').eq(0);
babyMoveText = $.trim(babyMoveCell.html());
secondEvoCell = babyMoveCell.next();
secondEvoText = $.trim(secondEvoCell.html());
finalEvo1Cell = secondEvoCell.next();
finalEvo1Text = $.trim(finalEvo1Cell.html());
finalEvo2Cell = finalEvo1Cell.next();
finalEvo2Text = $.trim(finalEvo2Cell.html());
//This checks if evolutions have checkmarks
if(babyMoveText.length > 0)
{
if(hasSecondEvo && secondEvoText.length == 0 || hasFinalEvo1 && finalEvo1Text.length == 0 ||
hasFinalEvo2 && finalEvo2Text.length == 0)
{
//See if the move is a TM before proceeding
var tm = tmCheck(moveName);
if(!tm)
{
if(secondEvoText.length > 0)
{
babyMoveCell.css("color", evoColor);
secondEvoCell.css("color", evoColor);
babyMoveCell.prev().find('a').eq(0).css("color", evoColor); //highlights move name
}
else
{
babyMoveCell.css("color", prevoColor);
babyMoveCell.prev().find('a').eq(0).css("color", prevoColor);
}
}
}
}
else if(secondEvoText.length > 0)
{
if(hasFinalEvo1 && finalEvo1Text.length == 0 || hasFinalEvo2 && finalEvo2Text.length == 0)
{
var tm = tmCheck(moveName);
if(!tm)
{
secondEvoCell.css("color", evoColor);
babyMoveCell.prev().find('a').eq(0).css("color", evoColor);
}
}
}
}
});
function tmCheck(input)
{
var isTM = false;
//Iterate through TMmoves array to see if the input matches any entries
for(var i = 0; i < TMmoves.length; i++)
{
if(input == TMmoves[i])
{
isTM = true;
break;
}
}
if(isTM == true)
return true;
else
return false;
}
//alert("evoColor: " + localStorage.getItem('evoColor') + ". prevoColor: " + localStorage.getItem('prevoColor'));
Any ideas as to why this is happening?
EDIT: I messaged sizzlemctwizzle about this problem, and this was his reply: "Tampermonkey’s #require implementation is incorrect. It downloads my updater far too often so I have banned it from using my updater via browser sniffing. My server just can’t handle the traffic it brings. The script it is downloading from my server shouldn’t have any actual code in it. Since it is causing errors with in your script I would guess Tampermonkey isn’t passing the User Agent header when it does these requests. I’m never tested my updater in Chrome so I have no idea why it breaks. Perhaps you could try and install NinjaKit instead."
What URL are you testing this on? I tested on http://veekun.com/dex/gadgets/stat_calculator.
Anyway, the script behavior, vis à vis the menu commands did seem erratic with Tampermonkey. I couldn't really tell / didn't really check if the rest of the script was working as it should.
The culprit seems to be the sizzlemctwizzle.com update check. Removing its // #require made the menu stable. Putting that directive back, broke the script again.
I've never been a fan of that update checker, so I'm not going to dive into why it appears to be breaking the Tampermonkey instance of this script. (That would be another question -- and one probably best directed at the 2 responsible developers.)
For now, suggest you just delete it. Your users will check for updates as needed :) .