Is it possible for a button to call a function that would 'prettify' a dynamic <code><pre>? I can't get it to work.
After the page loads, the initial <code> is prettified(?), but when I change it and call prettyPrint() afterwards, it no longer works.
Example: http://jsfiddle.net/uwBjD/2/
Edit: Sorry, I was using a local prettify.js. Updated it, still encountered the same error.
Apparently after the code is prettified, an additional class is added which is prettyprinted. Anything with the class of prettyprinted is not re-prettified. You need to remove that class before recalling the function:
$('input[type=button]').click( function() {
$("#jsExample").text(" var user = 'private'; //Do NOT store your API Key on a script.")
.parent().removeClass("prettyprinted");
prettyPrint();
});
http://jsfiddle.net/uwBjD/3/
Related
I found this question is already asked several times in different forms, but I still need some help on this, since can't get this as in the examples.
I have a JSF 2 page with PrimeFaces, and it contains the following hidden button, which I need to call on pageUnLoad from javascript.
The JSF has:
// Supposed to be hidden eventually
<h:commandButton id="doStuff" action="#{myBean.callMethod()}" />
The javascript has:
var stuff = new Object();
$(window).bind('beforeunload', function() {
stuff.doStuff();
});
stuff.doStuff = function() {
// var hidden = $("#doStuff"); // Incorrect
var hidden = document.getElementById("formId:doStuff"); // Correct
if (hidden === undefined) {
// Some logging
} else {
hidden.click();
}
}
And the managedBean has:
#ManagedBean(name = "myBean")
#RequestScoped
public class MyBean {
public void callMethod() {
// Do stuff
}
}
By debugging I can see that when manually clicking the button, it fires the event correctly.
I am also able to verify that the JavaScript is called correctly, it "seems" to find the element, and performs the '.click()' for it, but I do not catch any event on the server side.
I seem to be doing it as it has been instructed in other similar questions, but I lack the final result.
Any help would be appreciated, thanks.
Hidden button can be clicked by using JavaScript like
document.getElementById('doStuff').click();
However, you should be careful about naming containers. Hidden button must be enclosed by a <h:form> tag and prependid attribute of it should be set false. Otherwise you can access the button with the id formId:doStuff.
See also
Naming Container in JSF2/PrimeFaces
Cannot click hidden button by JavaScript
There is a much simpler way of calling server-side methods from javascript. Define a p:remoteCommand and Primefaces will create a JavaScript-function which you can call from inside your JavaScript-functions.
Use the following for defining the remoteCommand:
<p:remoteCommand name="doStuff" action="#{myBean.callMethod()}"/>
And then to call the bean-method on beforeunload just use:
$(window).bind('beforeunload', doStuff);
I have this JavaScript (with jQuery):
var g_files_added, socket, cookie, database = null;
var file_contents = [];
function viewFile(key, filename) {
$('#title-filename').text(filename);
$('.prettyprint').text(file_contents[key]);
$('#viewFileModal').modal('show');
}
$(document).ready(function() {
$(document).on('shown', '#viewFileModal', function(event) {
prettyPrint();
});
});
// Variables have been set in code not shown, irrelevant to problem.
// prettyPrint() is called everytime the #viewFileModal is shown,
// but its effect is only felt once.
So prettyPrint() is invoked every time the viewFileModal modal box (courtesy of Bootstrap) is shown, it's just that it only seems to have an effect once per page load.
I have tried commenting out prettyPrint() and entering at the JS console after making the modal box appear. It indeed only has an effect the first time the box is shown (per page load).
Any ideas? I have been stuck on this a while. I also tried putting the call to prettyPrint() in the viewFile function; but the effect is the same.
Thanks a lot.
Sam.
Calling "prettyPrint()" adds a class to your PRE tags named "prettyPrinted" after it has been prettified. The line below will remove all instances of the "prettyPrinted" class on your page so that the prettyPrint() function can re-prettify you're PRE tags. This can be done without dynamically adding PRE tags to DIVs.
$('.prettyprinted').removeClass('prettyprinted');
Thanks to Matei. Solution was to change to be like this.
That is, add whole pre dynamically rather than just text.
var g_files_added, socket, cookie, database = null;
var file_contents = [];
function viewFile(key, filename) {
$('#title-filename').text(filename);
$('#fileblock').html('<pre class="prettyprint">' + file_contents[key] + '</pre>'); // fileblock is a div.
$('#viewFileModal').modal('show');
}
$(document).ready(function() {
$(document).on('shown', '#viewFileModal', function(event) {
prettyPrint();
});
});
:)
Joseph Poff answer is correct but you have to be careful. prettPrint() wraps everything in scan tags. If you remove the prettyprinted class, you aren't removing the scan tags. Unless you are clearing the contents of your pre (or stripping out all the scan tags), every time you recall prettyPrint() you will be adding scan tags, which will wrap your old scan tags. It can get out of control really quickly.
In my HTML-head i have this script included:
<script id="mode" type="text/javascript" src="article.js"></script>
With a button click I'd like to change the source of the script to customers.js so that it then looks like this:
<script id="mode" type="text/javascript" src="customers.js"></script>
The point is that I don't want the article.js to be included in my page then anymore, so I can't just use .append().
So, click on the article button -> only article.js included, click on the customers button -> only customers.js included.
I tried to solve this with jQuery this way, but I doesn' seem to work...:
$("#btArticle").click(function(){
$("#mode").attr("src","article.js");
});
$("#btCustomers").click(function(){
$("#mode").attr("src","customers.js");
});
Do you know where my mistake is?
Update: There are methods with the same name in customers.js and article.js. So there's a onSave() method in both of them and when I clicked the customer button before, I want the onSave() method of customers.js to be executed, not the one in articles.js.
The point is that I don't want the article.js to be included in my page then anymore, so I can't just use .append().
Once the script has been downloaded and evaluated, anything it leaves lying around will remain unless explicitly removed; they're not linked to the script element itself and removing it won't have any effect on them.
The only way to get rid of the stuff article.js leaves lying around is to remove or overwrite each and every thing it creates and keeps.
Concrete example:
// article.js
var foo = "bar";
jQuery(function($) {
$(".stuff").click(function() {
alert("You clicked stuff!");
});
});
If the article.js listed above is processed, you can remove the script element that loaded it, and that will have no effect on the foo global variable or the event handler that it hooked up.
If you want to have scripts that you can unload, have them use the module pattern with a single global symbol they add by assigning to a property on window, e.g.:
// article.js
window.articleScript = (function() {
var foo = "bar";
jQuery(function($) {
$(".stuff").bind("click.article", function() {
alert("You clicked stuff!");
});
});
function remove() {
$(".stuff").unbind("click.article");
try {
delete window.articleScript;
}
catch (e) { // Early IEs throw incorrectly on the above
window.articleScript = undefined;
}
}
return {
remove: remove
};
})();
You can then remove it by doing this:
articleScript.remove();
Re your comment on the question:
Maybe I should've mentioned that there are methods in both files with the same name.
If you have global function declarations in customers.js that use the same name as global function declarations in articles.js, when you load customers.js, it will replace those functions.
So if you have this in articles.js:
function foo() {
alert("Articles!");
}
...and this in customers.js:
function foo() {
alert("Customers!");
}
And you have a button:
<input type="button" onclick="foo();" value="Foo">
When you've loaded just articles.js and not customers.js, clicking that button gives you "Articles!". If you then load customers.js, clicking the button will give you "Customers!".
That works because the event handler calls foo(), but the event handler itself is not foo. The onclick attribute creates a hidden event handler for you. The equivalent jQuery would be:
$("input[type='button'][value='Foo']").click(function() {
foo();
});
Note that just doing .click(foo) will do something very different: It will hook up the function that foo points to at that moment as the event handler. Even if you change what foo points to later (by loading customers.js), that won't change the fact that the old function is hooked up as a handler.
FWIW, from the question and your comments, I think I'd recommend sitting back and reviewing your strategy for this page/app. All of this swapping of code in and out and such seems like a design problem.
You are not actually loading and running the respective scripts, you are just changing the source for that tag. Use .getScript() to load and run the appropriate JavaScript file:
http://api.jquery.com/jQuery.getScript/
First I am using the jQuery colorbox plugin that is working fine so far but then I want to close the colorbox using a button. Unfortunately I can't just trigger the click event on that button by selecting its ID using jQuery, instead of that the button must call a javascript function called closepan() (this behavior is unfortunately mandatory for me).
I tried to create the function
closepan() {
$.colorbox.close();
}
first case : inside the
$(document).ready(function(){...});
but then I got the error closepan is undefined.
second case : before the
$(document).ready(function(){...});
but then it's the colorbox method that is undefined!
I gave up after gazillion hours of fiddling with several solutions I've found all around stackoverflow.com regarding this topic! I can't figure out how to make this working!
In other words, how to create a function named closepan() that can execute $.colorbox.close(); while being available globally for my button?
No matter where you create a variable or function if you create it on window it will be available globally.
window.closepan = function() {
// hello there
}
function closepan() {
if($.colorbox) {
$.colorbox.close();
}
}
However, at the point where someone clicks your button all external scripts should have been loaded so that check shouldn't be necessary...
Don't forget to put the keyword function in front of your declaration...
function closepan() {
$.colorbox.close();
}
Working JSFiddle
I am trying to give a button an onclick event when a certain thing on a page changes. I have tried to do it many different ways and none have worked. What am I doing wrong?
Below are what I have tried.
document.getElementById(subDiv).onclick = function() { alert('Error. There is an error on the the page. Please correct that then submit the page'); };
document.getElementById(subDiv).onclick = "alert('Error. There is an error on the the page. Please correct that then submit the page');";
function redErrorAlert()
{
alert('Error. There is an error on the the page. Please correct that then submit the page');
}
document.getElementById(subDiv).onclick = redErrorAlert;
document.getElementById(subDiv).setAttribute('onclick',redErrorAlert(), false);
document.getElementById(subDiv).setAttribute('onclick','redErrorAlert()', false);
Note: subDiv is a variable containing the id of the element.
You need to wait for the DOM tree to be created before you do queries on it.
Make sure that this all happens within a context that is created after the DOM tree has been built:
window.onload = function() {
document.getElementById(subDiv).onclick = function() { alert('Error. There is an error on the the page. Please correct that then submit the page'); };
};
document.getElementById() takes a string containing the ID of the element you're trying to find. Assuming you're looking for the element with id 'subDiv', you should be calling document.getElementById('subDiv').
(It's also possible that the variable subDiv in your code is a string containing the ID, but since you didn't mention it I'm assuming that it doesn't.)
EDIT: If you were to go with virstulte's suggestion of using jQuery, you'd attach a function to the document.ready event in order to ensure that the DOM has been built by the time your code runs. Example:
$(document).ready(function() {
$("#subDiv").click(function() { alert("Test!"); });
});
This sounds like jQuery territory here. Once you learn the ins and outs of jQuery, things like this are a snap to take care of, and you'll find yourself writing a lot less JavaScript.
First, get jQuery from http://jquery.com/
Then put this in your code to bind the event:
$('#idOfElementToBindClickEvent').click(function(){
alert('Error.');
});
jQuery basically provides a way to manipulate elements using CSS-like selectors.
try
document.getElementById(subDiv).onclick = alert('Error. There is an error on the the page. Please correct that then submit the page');
or
function redAlert() {
alert('Error. There is an error on the the page. Please correct that then submit the page');
}
document.getElementById(subDiv).onclick = redAlert();
First case: you need to call the function, and you've assigned a string
Second case: you've assigned a function and you were not calling this function