I have a problem with our website. I am trying to replace all occurrences of one phone number with different one.
If you go to www.paintballgames.co.uk you will see the regular page
If you go to www.paintballgames.co.uk/?test=phtest you will see one with changed number
However the rotator is not working in the second case.
I tried to compare source codes and only difference was, that in second case, I had some code that is changing the code displayed.
The code I am using is:
<script type="text/javascript">
var str = document.getElementById('forChange').innerHTML;
str = str.replace("844 477 5050", "844 477 5178");
document.getElementById('forChange').innerHTML = str;
</script>
Anyone can share any light on that?
First of all I see an exception with javascript even on the regular site:
$("#container-inline").html("<input type="image" name="op" value="GO" id="search-form-submit" class="form-image" />");
This will not work, as you should either escape quotes or use single quotes:
$("#container-inline").html("<input type=\"image\" name=\"op\" value=\"GO\" id=\"search-form-submit\" class=\"form-image\" />");
or
$("#container-inline").html("<input type='image' name='op' value='GO' id='search-form-submit' class='form-image' />");
UPDATE:
And one more exception in "click_heatmap.js":
Drupal.behaviors.click_heatmap = function()) {
// the "function()) {" is invalid. It should be "function() {"
click_heatmap.js:6 Uncaught SyntaxError: Unexpected token )
if (window.location.href != parent.location.href) {
$('#admin-menu').remove();
}
}
UPDATE 2:
It is possible, that after fixing the errors, you'll see the root of the problem.
UPDATE 3:
Why at all you are changing the phone number in Javascript and not on your server side?
UPDATE 4:
Now I've got even more interesting things! The 'forChange' element is almost the whole site wrapper! You should never write such code!
Instead of that you should have done this:
$(document).ready(function() {
$("SPAN.phone-now").text("your text");
});
UPDATE 5:
Now I can explain, why Javascript stops working. When you write something like body.innerHtml = body.innerHtml.replace(...) ALL the Javascript, which was there gets lost and the new one is not executed. So, nothing works! All references, which were saved in Javascript they point to not visible "old" elements.
Related
I'm a beginner with limited knowledge of both Javascript and html, sorry if my questions are very basic.
I'm trying to write a basic webpage that will do something to an array using Javascript when a button is clicked, then print the result to the page.
<!DOCTYPE html>
//error here
<html>
<head>
<title>Thursday's Homework</title>
<script>
var problem1 = function()
{for (var i = 0; i <= 50; i += 5) {
document.write(i + " ");
}
}
var myArray = []
var problem2 = function()
{for (var i = 0; i <= 9; ++i){
myArray[i]
}
document.write(myArray)
</script>
</head>
<body>
<center><h2><b> My Homework for Thursday<b></h2></center>
<p>This is my code for Problem 1:</p>
<input type="button" onclick = "problem1()" value="Does it work?">
//error here
<p>This is my code for Problem 2:</p>
<input type="button" onclick = "problem2()" value="Does it work?">
//error here
</body>
</html>
I'm getting three error messages when I debug in Chrome using developer tools:
After line 1: Uncaught SyntaxError: Unexpected end of input
After line 22(the first button): Uncaught ReferenceError: problem1 is not defined
After line 24(the second button): Uncaught Reference Error: problem2 is not defined
I'm also wondering if there's a better way to display the outputs than document.write because that makes it so that the page needs to be reloaded each time to see the next result.
I'm new, so my apologies if this is completely the wrong way to create this whole thing. If that's the case, just point me in the right direction.
UPDATE:
I've fixed the syntax errors and it's running fine. I'm still wondering about a better way to display my result that document.write. I'm not too knowledgeable, so if you have a suggestion, could you give me an idea of how to implement it?
You are missing a closing } after problem2.
That is the most common cause for this kind of error. The JS interpreter breaks since the function body is not properly closed, stops parsing. Then something else tries to reference a variable/function that failed to get parsed and triggers the Reference Error.
I can see a few issues.
You are missing a closing } after problem2.
You have spaces around your = for onclick =.
You're not actually doing anything with myArray. That does not seem intentional.
Your code formatting is unclear and that can lead to difficulties later (and I think this, in part, caused the bug). Unless you have a particularly good reason you should avoid things like {for. Instead add a newline after the {.
close the brace of problem2();
instead of document.write(); u can specify a id like
or
and in the js use
document.getElementById("abc").innerHTML=i+" ";
for better and safer coding use jsLint ..
As for you second question, you can find a lot of helpful extensions for both Chrome and Firefox that can satisfy you for debugging.
Chrome has internal tools such as "Web Console" that allow you to watch variables for exemple.
Javascript newb here. Creating a bookmarklet to automate a simple task at work. Mostly a learning exercise. It will scan a transcript on CNN.com, for instance: (http://transcripts.cnn.com/TRANSCRIPTS/1302/28/acd.01.html). It will grab the lead stories at the top of the page, the name and title of the guests on the show, and format them so that they can be copy pasted into another document.
I've come up with a simple version that includes some jQuery that grabs the subheading and then uses a regular expression to find the names of the guests (it will also exclude everything between (begin videoclip) and (end videoclip), but I haven't gotten that far yet. It then alerts them (will eventually print them in a pop-up window, alert is just for troubleshooting purposes).
I'm using http://benalman.com/code/test/jquery-run-code-bookmarklet/ to create the bookmarklet. My problem is that once the bookmarklet is created it is completely unresponsive. Click on it and nothing happens. I've tried minimizing the code first with no result. My guess is that cnn.com's javascript is conflicting with mine but I'm not sure how to get around that. Or do I need to include some code to load and store the text on the current page? Here's the code (I've included comments, but I took these out when I used the bookmarklet generator.) Thanks for any help!
//Grabs the subheading
var leadStories=$(".cnnTransSubHead").text();
//Scans the webpage for guest name and title. Includes a regular expression to find any
//string that starts with a capital letter, includes a comma, and ends in a colon.
var scanForGuests=/[A-Z ].+,[A-Z0-9 ].+:/g;
//Joins the array created by scanForGuests with a semicolon instead of a comma
var guests=scanForGuests.join(‘; ‘);
//Creates an alert in the proper format including stories and guests.
alert(“Lead Stories: “ + leadStories + “. ” + guests + “. SEE TRANSCRIPT FIELD FOR FULL TRANSCRIPT.“)
Go to the page. Open up developer tools (ctrl+shift+j in chrome) and paste your code in the console to see what's wrong.
The $ in var leadStories = $(".cnnTransSubHead").text(); is from jQuery and the link provided does not have jQuery loaded into the page.
On any modern browser you should be able to achieve the same results without jQuery:
var leadStories = document.getElementsByClassName('cnnTransSubHead')
.map(function(el) { return el.innerText } );
next we have:
var scanForGuests=/[A-Z ].+,[A-Z0-9 ].+:/g;
var guests=scanForGuests.join('; ');
scanForGuests IS a regular expression, you never actually matched it to anything - so .join() is going to throw an error. I'm not exactly sure what you're trying to do. Are you trying to scan the full text of the page for that regex? In that case something like this would be your best bet
document.body.innerText.match(scanForGuests);
keep in mind that while innerText removes html markup, it's far from perfect and what pops up in it is very much at the mercy of how the page's html is structured. That said, on my quick test it seems to work.
Finally, for something like this you should use an immediately invoked function or you're sticking all your variables into the global context.
So putting it all together you get something like this:
(function() {
var leadStories = document.getElementsByClassName('cnnTransSubHead')
.map(function(el) { return el.innerText } );
var scanForGuests=/[A-Z ].+,[A-Z0-9 ].+:/g;
var guests = document.body.innerText.match(scanForGuests).join("; ");
alert("Leads: " + leadStories + " Guests: " + guests);
})();
There is a page I can access that contains a bunch of links like this:
<a href="#" onclick="navigate(___VIEW_RAID_2, {raid_inst_id:556816});return false;">
The number after the raid_inst_id: is always going to be different and there will be multiples on the same page all with different numbers. I'm trying to put together a javascript that will scrape the page for these links, put them in an array and then cycle through clicking them.
Ideally, an alert causing a pause between onclicks would be helpful. I've been unsuccessful so far even trying to gather the numbers and just echoing them out let alone manipulating them.
Any hints or help would be greatly appreciated!
Below is a function I tried putting together just to see if I could capture some of the onclick values for further processing but, this produces nothing...
function closeraids(){
x=document.getElementsByTagName('a');
for(i=0;i<x.length;i++)
{
attnode=x.item(i).getAttributeNode('onclick');
alert("OnClick events are: " + attnode);
}
}
Wow - 4 months later and the same problem still exists. I decided to look into this again only to find my own posted question in my Google search! Does anyone have any thoughts on what could be done here? The function I'm trying to provide will be part of a Chrome extension I already provide to users. It uses a combination of a .js file I host on my webserver and injected html content.
Any help would be appreciated!
Had some fun while making this jsfiddle: http://jsfiddle.net/Ralt/ttkGG/
Mostly because I went onto using almost fully functional style... but well. Onto your question.
I'm using getAttribute('onclick') to get the string in there. It shows something like:
"navigate(___VIEW_RAID_2, {raid_inst_id:553516});return false;"
So I just built the necessary regex to match it, and capture the number after raid_inst_id:
var re = /navigate\(___VIEW_RAID_2, {raid_inst_id:(\d+)}\);return false;/;
It's mostly rewriting the string by escaping the parentheses and putting (\d+) where you want to capture the number. (\d+ is matching a number, () is capturing the matched string.)
Using match(), I can simply get the captured string as the last element. So, rewriting the code in old IE way:
var links = document.getElementsByTagName('a'),
re = /navigate\(___VIEW_RAID_2, {raid_inst_id:(\d+)}\);return false;/;
for (var i = 0, l = links.length; i < l; i++) {
var attribute = links[i].getAttribute('onclick'),
nb;
if (nb = attribute.match(re)) {
alert(nb.pop());
}
}
I have to create a javascript code which calls different images on the click of an image button. I have given names to the images as product1, product2, product3. I am new to JavaScript.
var count;
document.getElementById("divProduct").style.backgroundImage="url('images/product'+count)";
I am trying the above code, but it's not working
If you look at the syntax highlighting, + count is being treated as a string.
You put it outside of the single quotes (kind of), but you still need to put it outside of the double quotes, which are the quotes you're really using to delimit the string:
document.getElementById("divProduct").style.backgroundImage="url('images/product" + count + "')";
You are also missing the image extension. It should be .png or .jpg or something else depending on whatever type your image is.
Also I'd like to know if you are getting any errors on the console.
Edit : For those looking for answers to this question, please also check blender's reply below mine.
Your code should be like Blender said and still if it doesn't work add in you div
sample:
<div id="divProduct"> </div>
I think it must be like;
var count;
document.getElementById("divProduct").style.backgroundImage="url('images/product" + count + ".jpg')";
I have the following
var id='123';
newDiv.innerHTML = "";
Which renders in my HTML.
The problem I have is that I wish to take the call to the method TestFunction, and use as a string parameter in my function StepTwo(string, boolean), which would ideally end up in live HTML as shown...
notice how the TestFunction is a string here (it is executed within StepTwo using eval).
I have tried to format my JS as by :
newDiv.innerHTML = "";
but while this appears to me correct in my IDE, in the rendered HTML, it as garbelled beyond belief.
Would appreciate if anyone could point me in the right direction. Thanks!
One of the biggest capital failures on the internet is creating html in javascript by gluing strings together.
var mya = document.createElement("a");
mya.href="#";
mya.onclick = function(){
StepTwo(function(){
TestFunction('123', false );
}, true );
};
newDiv.innerHTML = "";
newDiv.appendChild(mya);
This Eliminates the need for any fancy escaping stuff.
( I probably should do 'onclick' differently, but this should work, I'm trying hard not to just use jQuery code to do everything )
Heres how I would do it in jQuery:
jQuery(function($){
var container = $("#container");
var link = document.createElement("a"); /* faster than $("<a></a>"); */
$(link).attr("href", "Something ( or # )" );
$(link).click( function(){
var doStepTwo = function()
{
TestFunction('123', true );
};
StepTwo( doStepTwo, false ); /* StepTwo -> doStepTwo -> TestFunction() */
});
container.append(link);
});
There is no good excuse for gluing strings together in Javascript
All it does is ADD overhead of html parsing back into dom structures, and ADD potential for XSS based broken HTML. Even beloved google get this wrong in some of their advertising scripts and have caused epic failures in many cases I have seen ( and they don't want to know about it )
I don't understand Javascript is the only excuse, and it's NOT a good one.
Try using " instead of \"
newDiv.innerHTML = "<a href="#"...
You should be using " not " or \" inside an HTML string quoted with double-quotes.
NewDiv.innerHTML = "";
There's probably a better way to do this - any time you find yourself using eval() you should stand back and look for a different solution.
You claim that eval is the right thing to do here. I'm not so sure.
Have you considered this approach:
and in your StepTwo function
function StepTwo(func,args,flag){
//do what ever you do with the flag
//instead of eval use the function.apply to call the function.
func.apply(args);
}
You could create the a element and attach to the click event using DOM Methods.
A Javascript Framework (like the ubiquitous jQuery) would make this a lot easier.
Your biggest problem is using eval, it leads to so many potential problems that it's nearly always better to find an alternative solution.
Your immediate problem is that what you really have is
as the next " after the start of the onclick attribute, closes it. Use " as others have suggested. And don't use eval.
You need to alternate your " and '.
Maybe you don't need quotes around the 123, because of Javascripts flexible typing. Pass it without quotes but treat it as a string within TestFunction.
Hey guys, thanks for all the answers. I find that the quot; seems to work best.
I'll give you guys some votes up once I get more reputation!
In regards to eval(), what you see in the question is a very small snapshot of the application being developed. I understand the woes of eval, however, this is one of those one in a million situations where it's the correct choice for the situation at hand.
It would be understood better if you could see what these functions do (have given them very generic names for stackoverflow).
Thanks again!
The best way is to create the element with document.createElement, but if you're not willing to, I guess you could do or use ".
In your code:
newDiv.innerHTML = "";
If it doesn't work, try changing "\'" to "\\'".
Remember that the " character is used to open and close the attribute on HTML tags. If you use it in the attribute's value, the browser will understand it as the close char.
Example:
<input type="text" value="foo"bar"> will end up being <input type="text" value="foo">.
...
I know this is hella' old now, but if anyone has issues with escaped strings when using eval (and you absolutely have to use eval), I've got a way to avoid problems.
var html = '';
eval('(function(div, html){div.innerHTML = html;})')(newDiv, html);
So, what's going on here?
eval creates a function that contains two parameters, div and html and returns it.
The function is immediately run with the parameters to the right of the eval function. This is basically like an IIFE.
In this case
var myNewMethod = eval('(function(div, html){div.innerHTML = html;})');
is basically the same as:
var myNewMethod = function(div, html){div.innerHTML = html;}
and then we're just doing this:
myNewMethod(newDiv, html); //where html had the string containing markup
I would suggest not using eval. If it can't be avoided, or if you control all the inputs and there's no risk of injection then this will help in cases where string escapes are an issue.
I also tend to use Function, but it isn't any more secure.
Here's the snippet I use:
var feval = function(code) {
return (new Function(code))();
}