Simple javascript document.write isn't working - javascript

Here's the code in question
I'm trying to create a simple application - each of the three men has a rel="x" attribute attached them. I'm using var regionId = $('img.selected-region').attr('rel'); to make the rel of the currently selected item the value of reginId.
I want to test this out by performing a simple document.write(regionId) command in a div under the pictures of the men. However, it's not working. Have I put the var regionId definition in the right place in the script window?
I'm completely new to javascript so the syntax is confusing to me - and help would be greatly appreciated.

Try this out http://www.jsfiddle.net/T6Jqx/15/
In the HTML, you have document.write in a script tag. At that time, the DOM may not be ready, but more importantly, it only executes once, not every time an image is clicked. I've modified it to print the "rel" attribute each time you click an image.

JSFiddle's script pane is executed after the document finishes loading.

Related

Chrome Extensions: Use a content script to modify existing scripts on a web page?

I'm creating a chrome extension that needs to hook into another script that already exists on my target web page. For simplicity's sake, I'm trying to find the following existing script element on a page and add a console.log() to it.
<script type="text/javascript">
var viewModel = new ScenePlayViewModel('', 'Ace', false);
viewModel
.load('jgWJJ2qsxx')
.then(function () {
sceneDOM = new SceneEditDOM2(viewModel.scene());
sceneDOM.init();
viewModel.isSubmitViaShareUrl(false);
viewModel.isSubmitViaUnityPackage(false);
console.log("HOOK INJECTED"); <--------------------------------------------- line to add
});
</script>
I've tried a number of solutions but none of them have seemed to work. For example, I've tried using a content script to find the script and replace the text, but it appears to run the pre-change script instead of my modified code.
// replaces javascript on website, but doesn't run new version
var scriptLoadScene = $("script:contains('new ScenePlayViewModel')"); // find the script
scriptLoadScene.text("console.log('Hello World')"); // change the text
What should I do? Basically, I'm just trying to change/add scripts to the web page to add more features.
This doesn't exactly answer your question, but hopefully will help you find a solution.
First - hopefully someone with more knowledge than me will confirm or discredit this - from my understanding, the script code is only run once, on page load, unless otherwise triggered by some event. Since Chrome extensions are triggered after the page has loaded, this script will have already been run, and anything inserted after won't run unless triggered.
I suppose you could always call the function again after you've edited it, but I don't have the knowledge or experience to predict what would happen then.
In my experience, I've just added my own '' tags with the code I wanted to run by writing them into the DOM, either into the '' or '' element.
Best of luck.
-brent

Script runs fine in the browser console, but not online

I'm working with a Wordpress website, where I'm building a navigation bar. One of the features I'd like to add is where if you're on a certain page, the option in the navigation bar will be bold to represent that is the section of the site you're visiting.
I'm attempting to achieve this using JavaScript, as I have no working knowledge of PHP:
var current_page = document.URL;
var current_option_id="";
if(current_page==="some-url"){
current_option_id="menu-item-34";
}
document.getElementById(current_option_id).getElementsByTagName("A")[0].style.fontWeight="bold";
Basically, my code figures out which page we're on, and will assign the right menu option's id to the current_option variable. Then, the script will attempt to select the
proper menu option, select the link inside that menu option, and change its style.
The problem with this script is that it simply won't work, generating an error where it cannot select the HTML element; document.getElementById(current_option); returns null. However, when I do this in the console, it works fine, and the style is changed properly. Why is this? I know that the current_option variable has the correct value, but the script fails when it tries to select the element to change.
Any suggestions and help are greatly appreciated. If you know how to do this in PHP with something that will integrate nicely with Wordpress, please do share (and explain how your code works!). If I broke any StackOverflow rule, my apologies.
it's hard to say without seeing your code, but is there a chance that your script is being executed before your entire page is loaded (or, more specifically, before the element with id #menu-item-34 has been added to the DOM)?
Try wrapping your script inside a function, and then setting that function as your page's onload handler:
window.onload = function() {
/* code goes here */
};

How to preprocess HTML before it is parsed by the browser - block resorce loading

I am looking for a way to modify some text inside the HTML before it is being parsed by the browser.
More precisely, I would like to remove some tags from the HTML so the image resources would not be fetched by the browser, only when I am ready I could insert these tag back to have them loaded.
Is it possible to do that via some JS/Jquery or CSS, if so, how?
the motivation here is to be able to block the loading of some resources on a page and have them loaded only when needed according to some logic. this needs to be done by some kind of scripting added to the page
Because you're doing this in JavaScript the HTML is already being processed when it comes to launch your <script> tags.
You could move your <script> tags into the <head> from the <body>, or move it to the very beginning of the body. However the problem here is that you'll have to wait for your elements to actually be created in the DOM before you can work with them.
You could use something like setTimeout() or similar and continually look for them until you find them, but there's still going to be a slight delay between them being created and your script finding them, at which point they might already start to load.
The only surefire way is to process the markup server side long before it gets to the browser.
My answer here possibly could be of use, if you can place noscript tags in key places in your markup prior to parsing/evaluation:
Client-Side Dynamic Removal of <script> Tags in <head>
This method—for javascript-enabled agents—would delay the rendering of the entire page however, or at least the regions that you needed to affect.
basic generalised theory
Wrapper your body or specific region with a noscript tag identified with either a class or id. Place some javascript to execute directly after the close noscript that grabs the tag and reads the html contents as a string. At this point you could modify the html string however you like and then re-inject it back into the DOM replacing the noscript tag.
more specific implementation
If you know before-hand which resources you need to postpone—say all your images—you could wrap each image in-question with a noscript tag. Then trigger off some JavaScript that grabs all noscripts and rewrites the contained image html to use a placeholder or lower quality version of the image. At the same time you could set up event listeners or timeouts that inject the actual images when the time is right.
The Lazy Load Plugin for jQuery is maybe what you are looking for. It delays loading of images in long web pages.
You can use any jQuery event such as click or mouseover. You can also use your own custom events such as foobar. Default is to wait until user scrolls down and image appears on the window.
Beside all the It is also possible to delay loading of images. Following code waits for page to finish loading (not only HTML but also any visible images). Five seconds after page is finished images are loaded automatically.
$(function() {
$("img:below-the-fold").lazyload({
event : "sporty"
});
});
$(window).bind("load", function() {
var timeout = setTimeout(function() {
$("img.lazy").trigger("sporty");
}, 5000);
});
Check the delayed loading demo.

Dynamically generate a webpage in GWT

I have a unique challenge that I'm not sure how to approach:
I need to manufacture a new HTML page from scratch, one that contains a script tag and a paragraph tag with some words in it. Very simple! Once the page is built, I just need to open it in a new tab. As long as a I can call the script tag from within it, a popup is fine too. Basically, I am going to use a library called MathJax which will typeset all the elements on the html page it loads on.
I'm not even sure what this functionality is formally called, or if it's even possible in GWT! Any guidance at all would be appreciated, thanks!
There is no need to use GWT for it. Just write simple servlet that will spit out html with required script tags to load GWT and do whatever else you need and you are done.

Using jQuery to change dynamic content?

I'm pretty new to using jQuery but am working on a Safari Extension at the moment and have run into a bit of a puzzle with appending some text to a page.
Basically, I am creating an extension that will append a specific string of text with another on the page within an element
<td id="name">foo</td>
Using the following jQuery code
jQuery("#name").filter(function()
{return jQuery(this).text() == 'foo'; }).append('bar');
This would result in
<td id="name">foobar</td>
This works great in a standard html page, however - the site I wish it to run on uses a different bit of JS to dynamically load the content within the element, so when testing it on the site, the element is listed as
<td id="name"></td>
and then the JS library adds the name to it, meaning I cannot append the text (the name appears in the browser window but not within the page's source). Is there a way I can get around this?
I've tried using
$(window).load()
Though this had no effect.
It just sounds like you need to delay your script so it will run after the other script that is writing "foo" runs. Generally jquery scripts are run on document load with
$(function(){ /* script */ });
so if that is too early you may need to bind to some event that is occuring when "foo" is written that you might have to hook onto your other script for. Its not clear from the question is this is an ajax thing that writes "foo" or just another script that doesn't have any additional load. You might want to post that.
If you still can't figure it out, you can always use a setTimeout() call to delay your script, but that is sloppy and not recommended.

Categories

Resources