JavaScript - Bookmarklet, Indexof And If/else
Hi,
I am trying to build a bookmarklet to use on the swiss legislation website. All the pages are available in several languages and I want to be able to switch with one button from french to german and from german to french. As an example, the URLs are as follow for the same page: in French: http://www.admin.ch/ch/f/rs/311_0/index2.html in German: http://www.admin.ch/ch/d/sr/311_0/index2.html So I built quite easily two bookmarklets to switch FR-DE and DE-FR: Code: javascript: var str = window.location.pathname;str = str.replace("f/rs", "d/sr");window.location = str; Code: javascript: var str = window.location.pathname;str = str.replace("d/sr", "f/rs");window.location = str; But when I try to get a single script by using if/else, I cannot manage to have the "else" part working: Code: javascript: var str = window.location.pathname; if (location.pathname.indexOf("d/rs") < 0) { str = str.replace("f/rs", "d/sr"); window.location = str; } else { str = str.replace("d/sr", "f/rs"); window.location = str; } Thinking it might have to do with str.replace, I tried an easier variant, but even this one does not work, the "else" part is never called: Code: javascript: var str = window.location.pathname; if (location.pathname.indexOf("d/rs") < 0) { str = str.replace("f/rs", "d/sr"); window.location = str; } else { alert('no'); }; I would appreciate any help on the matter... thanks in advance, RJ Similar TutorialsThis is a snippet from a project I'm working on involving XML DOM, but the question is really about javascript. This is the problematic code. Code: else if (nodeOccurance.IndexOf('each:') == 0) { . . . } I want the if statement to be true if the value of the variable "nodeOccurance" begins with "each:" For some reason, it's just stopping my whole script and doing nothing. Any help? Thanks, Julian Hello there I'm trying to build a simple little bot that you can ask questions. I'm using the indexOf method but I'm not sure if this is the best option for what I'm trying to do. If you type 'hello' or 'how are you' it answers. Any other input results in 'Dreadfully sorry but I didn't catch that. Say again?'. Is there a way that I can search input for certain words or combinations of words and trigger a single answer? Any help appreciated. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Bot</title> <script type="text/javascript"> function bot(go){var a = go.getElementsByTagName('input');var q = a[0];var t = q.value.toLowerCase();document.go.reset();if(t.indexOf('hello')!=-1){document.getElementById('bot').innerHTML = "Hello to you.";return false;}if(t.indexOf('how are you')!=-1){document.getElementById('bot').innerHTML = "I am functioning within acceptable parameters, thank you.";return false;};go.action=document.getElementById('bot').innerHTML = "Dreadfully sorry but I didn't catch that. Say again?"; return false;}; </SCRIPT> </head> <body onLoad="document.go.q.focus()"> <div align="center"> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <form name="go" onsubmit='return bot(go)' id="go" action=""><input name='q' type='text' /><input name='' type='hidden' /></form> <p> </p><div id="bot" align="center"></div> </div> </body> Hi, I'm trying to match a text string within a textarea node and then use a text range to set the users cursor highlighting over the word.My code for this is as follows: Code: function doHighlight(theWord, textAreaElement) { var text = textAreaElement.value; var theIndex = text.indexOf(theWord); setCaretPos(textAreaElement, theIndex, theIndex+theWord.length); } function setCaretPos(obj, start, end) { var range = obj.createTextRange(); range.moveStart('character', start); range.moveEnd('character', end - obj.value.length); range.select(); } I have a text area with the following html: Code: <TEXTAREA>blah blah sausage Frank Jones</TEXTAREA> (ie there are four lines visible to the user, the 3rd is blank). And I call the doHighlight method with 'blah blah', 'sausage' and 'frank jones' respectively. However the highlighting isnt working quite right - when I try to highlight 'blah blah', it highlights 'blah bl', when I try to highlight 'sausage' it highlights 'ausa' (the 2nd-5th characters) and when I try to highlight 'frank jones', it highlights 'nk jones'. This code seems to work fine when there is only a single line of text in the text area though - so I'm guess it's something to do with newline characters. Can anybody point me in the right direction as to how to fix this bug please? Thanks. hi all, my indexof() function is not being recognized when I enter an email address for an unsubscribe form I have on one of my pages. Additionally, the confirmation message is also not showing up when the email address IS valid. Here is my code that I am using on a PHP page: PHP Code: function Unsubscribe() { var IsValid = document.getElementById("email").value; alert(IsValid.indexOf("@")); exit; if (document.getElementById("email").value.length == 0 || IsValid.indexOf("@")) == -1) { alert("Enter a valid email address"); exit; } else { <?php $handle = @fopen("../logs/unsubscribes.txt", "a"); fputs($handle, $_POST["email"] . " " . "\r\n"); fclose ($handle); ?> alert(IsValid &&" has been unsubscribed."); <?php if (! $_POST["email"]) { //DO NOTHING } else { header("Location: http://www.google.com/"); } ?> } } //--> </script> </head> <body> <form action="" method="post" name="frm" onsubmit="Unsubscribe()"> <center><br /> Enter Your Email Address:<br /> <input type="text" id="email" name="email" /> </center> <p> <label> <center><input type="submit" id="unsubscribe" value="Unsubscribe Me" /></center> </label> </p> </form> </body> </html> to those PHP experts, I am aware of the RegEx function for validation, but I don't understand it, which is why I don't use it (in case anyone points that out). The other thing that is problematic is that the PHP code is automatically using HEADER() regardless of "email"'s value 0 down vote favorite share [g+] share [fb] share [tw] I have a fairly large program that I have simplified to show the problem that I am having. I have 2 div's under which I have an image and some text. When I hover on the image, the jQuery hover over image event fires. Through all this, I am able to get the Id's of both the images & their parent div's. However, when I try to get the index value of the Id's in an array, it always returns -1 ie... not found. Can you please help. The code is enclosed below. I am new to javascript & jQuery and hence the need of some help. Maybe the solution is very trivial. Thanks in advance. Regards, sbguy <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> var input_array = new Array("input1_Id", "input2_Id"); var div_array = new Array("div1_Id", "div2_Id"); window.onload=function(){ jQuery.ready(); img_hover_event_handler(); } //________________________________________________ function img_hover_event_handler() { var input_id = ""; var div_id = ""; var input_index, div_index; $("input.Lrollover").hover( function() { input_id = new String(this.id); input_index = new String(input_array.indexOf(div_id)); div_id = new String($(this).closest('div').attr('id')); // id of the parent div div_index = new String(div_array.indexOf(div_id)); alert(input_id + ", " + input_index + ", " + div_id + ", " + div_index); }, function() { }); } </script> </head> <body> <div id="div1_Id"> <input class="Lrollover" id="input1_Id" type="image" src="images/LGbtn_off.png" alt="Image1" /> <p id="myp1_Id">"Hello World 1"</p> </div> <br><br><br> <div id="div2_Id"> <input class="Lrollover" id="input2_Id" type="image" src="images/LGbtn_off.png" alt="Image2"/> <p id="myp2_Id">Hello World 2"</p> </div> </body> </html> Hi there! OK I need a little help as I'm not sure how to integrate this function into my form. First of all I should explain that my form doubles as a Google Search box. If you select the Google Search radio button it submits the input text to Google. It also defaults to Google if anything else other than "red", "green" or "blue" are entered. Now what I'd like to do is add a function so that if someone enters "purple is my favorite color" it recognizes the "purple" part of the string using something like .indexOf('purple'); and calls something like if(function==-1) { theForm.action = "Other choice "+ q.value; . How can I add this to my form? Thank you for any help. My form code: Code: <script> function convert(theForm){ var els = theForm.getElementsByTagName('input');// store inputs var q = els[0], color = els[1]; if(els[4].checked){// submit to google theForm.action = 'http://www.google.com/search'; return true; }; color.value = "Chosen "+ q.value +" color"; switch(q.value){// check the query case 'red': case 'green': case 'blue': location.href = color.value; return false; break; default: theForm.action="http://www.google.com/search"; break; }; return true; }; </script> <form name= "myform" onsubmit='return convert(this)'> <input name='q' type='text' /> <input name='color' type='hidden' /> <input type='submit' value=" Enter " /> <br /> <input name="searchType" type="radio" value="" checked="checked" > <label for="all"> My Form </label> <input name="searchType" type="radio" value="google" onclick="document.myform.action='http://www.google.com/search';" /> <label for="google"> Google Search </label></form> Hi there, I hope this is the right Forum for asking this. I'm trying to build a Bookmarklet for our Institute, which should work with our library repository. The idea is to consult a SQL search within the repository using the serial number of an article or book which is imported into the bookmarklet via getSelection. Then, after the search query is completed, the repository homepage prompts to the results page. This is where I get stuck. The bookmarklet should now simply show a prompt window saying: do you see a found result on this page? Yes or No. If the user clicks nno, the bookmarklet should forward to the import page, if Yes, the entry is already in the repository and the import is unneccessary. javascript:Qr=document.getSelection();if(!Qr)%7Bvoid(Qr=prompt('Please%20type%20repository&20Nr.:',' '))%7D;if(Qr)location.href='http://dali.biologie.uni-ulm.de/refbase-0.9.5/search.php?formType=sqlSearch&submit=&citeStyle=&citeOrder=&sqlQuery=SELECT+author%2C+title%2C+year% 2C+publication%2C+volume%2C+pages+FROM+refs+WHERE+doi+RLIKE+%22'+escape(Qr)+'%22+OR+notes+RLIKE+%22' +escape(Qr)+'%22+ORDER+BY+year+DESC%2C+author&showLinks=1&showRows=30&viewType=Web'; if(confirm('Is%20the%20article%20already%20in%20the%20repository?')) location.href='http://dali.biologie.uni-ulm.de/refbase-0.9.5/import_modify.php?formType=importID&submit=Import&showSource=1&sourceIDs='+escape(Qr) I hope this is not too confusing. Thanks to anyone for help, and have great holidays! Can someone tell me what I am doing wrong here... This returns "Button Not Found" Code: javascript:var nam="http://apps.facebook.com/onthefarm/giftaccept.php?senderId=547766125&gift=haitibackpack_item_single&timestamp=1285776944&ref=gift_accept_tab&key=6870697de39960508737349c7a3f1363%24%24ggM3T%2CPU2YKM2l0mNrM%28U%28b%21eHAoclFCBgwg49%21S34GWkEXxTekFN_Fkx5%2AUZPcNMEOj&signature=a86a9e11aab0051e3fde676a9abe4283&srcapp=FarmVille"; nam="actions["+nam.replace(/\&/g, "&")+"]"; var els=document.getElementsByName(nam); if(els.length == 0) alert("Button not found"); else els[0].click(); This prompts me to enter a URL...I enter the EXACT same URL as in the above example and it works fine, clicks the button which brings me to the desired page. Code: javascript:var nam=prompt('enter URL Please'); nam="actions["+nam.replace(/\&/g, "&")+"]"; var els=document.getElementsByName(nam); if(els.length == 0) alert("Button not found"); else els[0].click(); Thanks Edit: Before you ask...I've tried in Chrome, IE and Firefox. It does not appear to be an issue with the length of the JS. I get the same results as above regardless of which (valid) URL I use. Hi, I'm trying to make a JavaScript where when it's clicked, two alert input boxes appear and the user inputs two Facebook users' ID numbers. The script should then load an iFrame with: ttp://www.facebook.com/"+s+"?and="+s2+" Where "s" and "s2" are the variables. Why is the following not working? Code: if (typeof jQuery == 'undefined') { var jQ = document.createElement('script'); jQ.type = 'text/javascript'; jQ.onload=runthis, runthis2; jQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'; document.body.appendChild(jQ); } else { runthis(), runthis2(); } function runthis() { if ($("#wikiframe").length == 0) { var s = ""; s = getSelText(); if (s == "") { var s = prompt("Person 1"); } if ((s != "") && (s != null)) { $("body").append("\ function runthis2() { if ($("#wikiframe").length == 0) { var s2 = ""; if (s2 == "") { var s2 = prompt("Person 2'"); } if ((s2 != "") && (s2 != null)) { $("body").append("\ <div id='wikiframe'>\ <div id='wikiframe_veil' style=''>\ <p>Loading...</p>\ </div>\ <iframe src='http://www.facebook.com/"+s+"?and="+s2+"' onload=\"$('#wikiframe iframe').slideDown(500);\">Enable iFrames.</iframe>\ <style type='text/css'>\ #wikiframe_veil { display: none; position: fixed; width: 100%; height: 100%; top: 0; left: 0; background-color: rgba(255,255,255,.25); cursor: pointer; z-index: 900; }\ #wikiframe_veil p { color: black; font: normal normal bold 20px/20px Helvetica, sans-serif; position: absolute; top: 50%; left: 50%; width: 10em; margin: -10px auto 0 -5em; text-align: center; }\ #wikiframe iframe { display: none; position: fixed; top: 10%; left: 10%; width: 80%; height: 80%; z-index: 999; border: 10px solid rgba(0,0,0,.5); margin: -5px 0 0 -5px; }\ </style>\ </div>"); $("#wikiframe_veil").fadeIn(750); } } else { $("#wikiframe_veil").fadeOut(750); $("#wikiframe iframe").slideUp(500); setTimeout("$('#wikiframe').remove()", 750); } $("#wikiframe_veil").click(function(event){ $("#wikiframe_veil").fadeOut(750); $("#wikiframe iframe").slideUp(500); setTimeout("$('#wikiframe').remove()", 750); }); } function getSelText() { var s = ''; if (window.getSelection) { s = window.getSelection(); } else if (document.getSelection) { s = document.getSelection(); } else if (document.selection) { s = document.selection.createRange().text; } return s; } I'm trying to write a bookmarklet to automatically follow a specific link on a page without manually clicking or selecting the link. It's for the Facebook game Hatchlings. Each time I view someone's page to collect an egg, it has the following text: You found an egg! Add it to your basket. "Add it to your basket." is the clickable link, but has a different URL embedded in it each time I visit the page. Is there a way to create a bookmarklet to strip out the embedded URL and go to the link without actually clicking on "Add it to your basket." ? Thanks in advance for the help. Hi, I want to open a new window and then execute some js function on that window. My code looks like this: Code: windowObjectReference = window.open("http://some_page.html","name"); windowObjectReference = window.open("javascript:(some_function('param1');)","name"); Is it possible to do activate bookmarklet thru js on new window? Hello all i need to be able to make small peace of js code that the user can drag to is IE browser and then invoke it on the page . Simple enough, one would think, but I'm rusty and haven't done this kind of thing in years. All I need to do is take the current page's url and replace/add a bit into the URL at the appropriate place. For Example, if this is the Current Page URL: Code: http://www.mysite.com/section/main.php?p=1 I want to be able to use the bookmarklet to change it to: Code: http://www.mysite.com/section2/main.php?p=1 This is all I've got for it so far. Probably botched that up too. Code: javascript:(function(){var%20a=document.URL.split("/section/");var%20newURL="www.mysite.com/section2/"+a;}) Hey all - I need a java bookmarklet that does a real simple thing. I need to take the current URL (ie, where the user is when they click the bookmarklet) and append it to a static URL and return the text on the resulting page. For example: The user is at http://google.com The user clicks the bookmarklet. the bookmarklet takes http://google.com and appends it to http://example.com/outside_create.ph...ey=555&url=URL HERE where you see the URL HERE text. That PHP script echos a simple line of text (a shortened URL actually). Then I want that result from the outside_create.php file to be displayed in a window back to the user. Is this even possible? Basically I need to know how to append location.href to a static URL and how to get the resulting content from the static URL.. hi guys, How could I make this useful dictionary bookmarklet open in a new window? javascript:var%20t=((window.getSelection&&window.getSelection())||(document.getSelection&&document.g etSelection())||(document.selection&&document.selection.createRange&&document.selection.createRange( ).text));var%20e=(document.charset||document.characterSet);if(t!=''){location.href='http://translate.google.com/translate_t?text='+t+'&hl=en&langpair=auto|en&tbb=1&ie='+e;}else{location.href='http://translate.google.com/translate?u='+escape(location.href)+'&hl=en&langpair=auto|en&tbb=1&ie='+e;}; Its the "To English" bookmarklet as featured on lifehacker. Thanks! I'm not very well versed in javascript. I'm trying to make a bookmarklet that when I click it will either append text to what I've already written or insert the predefined text at the cursor's position in a textarea. Also the browser I'm trying to do this on is Chromium. Here's what I have: Code: javascript:void((function(){document.getElementsByTagName('textarea')[0].value='ಠ_ಠ'})()) ...but this of course changes the entire value of the text field to: ಠ_ಠ ...rather than appending or inserting at the cursor position. I'm guessing append would be the simplest, though cursor position would be most efficient. So if you can help in anyway, please do! Thanks. Hi, It would be easier to explain this if you play mafia wars (or any game that includes intra-game exchange of gifts/items between members) but the actual scripting doesn't require any knowledge of the game. Background Information Mafia Wars is a game on Facebook (and myspace, yahoo etc.) that among other things allows its players to send gifts to each other. Now because different people end up with more things of one type and are short of things of another type, the players have evolved a trading dynamic. Where x number of Item 1 is traded for y number of Item 2. A simple marketplace. And with this territory come scammers. Essentially a player who doesn't go through with his end of the deal. good player sends item to bad player. bad player removes good player from mafia and blocks him for ever contacting him through his facebook profile. This has given rise to my group, among many others, that lists these scammers (identified with their facebook profile ids) as they are reported every day. Now over time the list has grown and it has become difficult and unrealistic to expect people to know who is on the list and who is not. The Requirement A javascript bookmarklet (there are many already servicing different needs of the players) that sits on the browser and tells the user if the person he is about to trade with is a listed scammer or not. The Breakdown The user will click the bookmarklet when he is on the facebook profile of the person he is about to trade with. When clicked the script will pull the facebook profile id from the current page, and then scan a text file located on a third-party server and return with a pop-up box message that reports if the id is listed as a scammer or not. It should be pretty simple to do, except I don't know the first thing about javascript coding. So if there's anyone who can devote a few hours/days to help us out with this it would be greatly appreciated. Thank you. Hi, It would be easier to explain this if you play mafia wars (or any game that includes intra-game exchange of gifts/items between members) but the actual scripting doesn't require any knowledge of the game. Background Information Mafia Wars is a game on Facebook (and myspace, yahoo etc.) that among other things allows its players to send gifts to each other. Now because different people end up with more things of one type and are short of things of another type, the players have evolved a trading dynamic. Where x number of Item 1 is traded for y number of Item 2. A simple marketplace. And with this territory come scammers. Essentially a player who doesn't go through with his end of the deal. good player sends item to bad player. bad player removes good player from mafia and blocks him for ever contacting him through his facebook profile. This has given rise to my group, among many others, that lists these scammers (identified with their facebook profile ids) as they are reported every day. Now over time the list has grown and it has become difficult and unrealistic to expect people to know who is on the list and who is not. The Requirement A javascript bookmarklet (there are many already servicing different needs of the players) that sits on the browser and tells the user if the person he is about to trade with is a listed scammer or not. The Breakdown The user will click the bookmarklet when he is on the facebook profile of the person he is about to trade with. When clicked the script will pull the facebook profile id from the current page, and then scan a text file located on a third-party server and return with a pop-up box message that reports if the id is listed as a scammer or not. It should be pretty simple to do, except I don't know the first thing about javascript coding. So if there's anyone who can devote a few hours/days to help us out with this it would be greatly appreciated. Thank you |