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.
Related
Weird problem. I'm modifying shop template:
https://demo.themeisle.com/shop-isle/product-category/clothing/dresses/
At this moment when you hover product's picture there will show "add to cart" button. This is .
Under picture there is price
I prepared code:
var from = document.getElementsByClassName("woocommerce-Price-amount amount");
jQuery(document).ready(function(){
jQuery.each(from, function(i, el) {
jQuery(el.parentNode.parentNode).find(jQuery(".product-button-wrap")).append(el);
});
});
Nothing happens. This code work only if I set timeout:
setTimeout(function() {
var from = document.getElementsByClassName("woocommerce-Price-amount amount");
jQuery(document).ready(function(){
jQuery.each(from, function(i, el) {
jQuery(el.parentNode.parentNode).find(jQuery(".product-button-wrap")).append(el);
});
});
}, 10000);
Of course timeout it's not a solution. I was trying to find out minimal time to obtain best behavior but it's impossible. I have feeling that every browser (and version...) needs personalized time setting.
I thought that after 24-hour break I will get some brillant idea, but that doesn't work, no more ideas.
--- EDIT ---
OK, thanks for pointed mixed common js with jquery - I will correct that later.
jQuery(document).ready(function(){
var from = document.getElementsByClassName("woocommerce-Price-amount amount");
jQuery.each(from, function(i, el) {
jQuery(el.parentNode.parentNode).find(jQuery(".product-button-wrap")).append(el);
console.log(el);
});
});
That's logical that var from should be inside ready but this still doesn't work. No effect.
If I use in loop console.log it will return for me html code of el.
--- EDIT ---
Thanks. While testing I noticed something. I wanted append element .woocommerce-Price-amount.amount to element .product-button-wrap. But how can I do that if element .product-button-wrap isn't originally in source? This object is created dynamically (I don't know how).
-- EDIT --
OK. I checked JS files and found code adding to DOM .product-button-wrap so I putted my code there and now everything works. Thanks for help.
The problem is because you're running your code before the DOM has loaded. You need to retrieve the elements within the document.ready event handler.
Also note that you have an odd mix of native JS and jQuery methods. I'd suggest using one or the other, like this:
jQuery(function($) {
$('.woocommerce-Price-amount.amount').each(function() {
$(this).parent().parent().find('.product-button-wrap').append(this);
});
});
Also note that .parent().parent() should be replace by a single call to closest(), but I can't give you an exact example of that without seeing your HTML.
I'm fairly new to Javascript, and am trying to get an 'on click enlarge' kind of effect, where clicking on the enlarged image reduces it again. The enlarging happens by replacing the thumbnail by the original image. I also want to get a slideshow using images from my database later on.
In order to do that, I made a test where I replace the id which indicates enlarging is possible by a class and I also use a global variable so that I can keep a track of the url I'm using. Not sure this is the best practice but I haven't found a better solution.
The first part works fine, my image gets changed no problem, values are also updated according to the 'alert' statement. However, the second part, the one with the class never triggers.
What am I doing wrong (apart from the very likely numerous bad practices) ?
If instead of changing the class I change the id directly (replacing .image_enlarged by #image_enlarged, etc.), it seems to call the first function, the one with the id, yet outputs the updated id, which is rather confusing.
var old_url = "";
$(function(){
$('#imageid').on('click', function ()
{
if($(this).attr('class')!='image_enlarged'){
old_url = $(this).attr('src');
var new_url = removeURLPart($(this).attr('src'));
$(this).attr('src',new_url); //image does enlarge
$(this).attr('class',"image_enlarged");
$(this).attr('id',"");
alert($(this).attr('class')); //returns updated class
}
});
$('.image_enlarged').on('click', function (){
alert(1); //never triggered
$(this).attr('src',old_url);
$(this).attr('class',"");
$(this).attr('id',"imageid");
});
});
function removeURLPart(e){
var tmp = e;
var tmp1 = tmp.replace('thumbnails/thumbnails_small/','');
var tmp2 = tmp1.replace('thumbnails/thumbnails_medium/','');
var tmp3 = tmp2.replace('thumbnails/thumbnails_large/','');
return tmp3;
}
As for the html, it's really simple :
<figure>
<img src = "http://localhost/Project/test/thumbnails/thumbnails_small/image.jpg" id="imageid" />
<figcaption>Test + Price thing</figcaption>
</figure>
<script>
document.write('<script src="js/jquery-1.11.1.min.js"><\/script>');
</script>
<script type="text/javascript" src="http://localhost/Project/js/onclickenlarge.js"></script>
From the API: http://api.jquery.com/on/
The .on() method attaches event handlers to the currently selected
set of elements in the jQuery object.
When you do $('.image_enlarged').on(...) there is no element with that class. Therefore, the function is not registered in any element.
If you want to do so, then you have to register the event after changing the class.
Here's an example based on your code: http://jsfiddle.net/8401mLf4/
But this registers the event multiple times (every time you click) and it would be wrong. So I would do something like:
$('#imageid').on('click', function () {
if (!$(this).hasClass('image_enlarged')) {
/* enlarge */
} else {
/* restore */
}
}
JSfiddle: http://jsfiddle.net/8401mLf4/2/
Try using:
addClass('image-enlarged')
instead of:
.attr('class',"image_enlarged");
the best way to do this would be to have a small-image class and a large image class that would contain the desired css for both and then use addClass() and removeClass depending on which you wanted to show.
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/
I would like to refire the styling and processing.js scripts that i linked to in the head so that they display correctly when brought in through an ajax-request. I see where in the ajax request this code needs to be, but i don't know how to tell the code to simply reapply the script. I've seen people using getScript() to do this, but from what i can tell this reloads the script, rather than simply telling it repeat or refire. Do all of the scripts need their own reinitialization? I found the syntax highlighters .highlight() method, but i am yet to get the processing script to load. currently, Processing.loadSketchFromSources($('#processing'), ['mysketch.pde']); does not work. I am using current versions of all libraries. Surprised i haven't been able to find the answer yet, as a lot of people seem to have the same problem. Thanks for your help!
index page:
$(document).ready(function () {
// put all your jQuery here.
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Search for link with REL set to ajax
$('a[rel=ajax]').live("click",function(){
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content and show the progress bar
//$('#content').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
function getPage() {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
//display the body with fadeIn transition
$('#content').fadeIn('fast');
//reapply styles?
//apply syntax highlighting. this works
SyntaxHighlighter.highlight();
//relaod processing sketch, currently displays nothing
Processing.loadSketchFromSources($('#processing'), ['mysketch.pde']);
}
});
}
This the ajax-loaded content:
<!--ajax'd content-->
<??>
<h2>code</h2>
<pre class="brush: php">
$last_modified = filemtime("header.php");
echo("last modified: ");
echo(date("m.j.y h:ia", $last_modified));
</pre>
<script type="application/processing">
</script>
<canvas data-processing-sources="mysketch.pde" id="processing">
</canvas>
</div>
</body>
</html>
<??>
So, let's analyze what usually happens when you include an (external or internal) Javascript code: It will automatically execute only the code that is available in the global scope. "Good" scripts will only add one command to the global scope which will then execute the initialization code somewhere in a function/method.
All you need to do is view the external Javascript file and find out what is being executed from the global scope. There is no general answer to that ... some scripts use an object and call its init() method ... but that is totally subject to the imagination of the developer.
If you have javascript that needs to trigger, you MUST add this to the head element:
var head = document.head || document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.innerHTML = "your AJAX-obtained js code";
head.appendChild(script);
The same trick goes for CSS. Add a element to the head with your CSS declarations as innerHTML. So: make sure to preprocess your AJAX response and split out the JavaScript and CSS elements, then add those to the document header. It's probably easier to make your response a JSON object along the lines of:
{
html: "<html>string<goes>here</goes></html>",
scripts: ["url1","url2","url2",...],
style: ...
}
and then parsing that JSON for the html (which you use as innerHTML for a new document.createElement("div") or something, and then append wherever it needs appending), the scripts (which you turn into elements for HEAD insertion) and the style declarations (which you turn into elements for HEAD insertion).
(On a functional note, your example AJAX response looks like it has PHP code in it. I have no idea what you're using it for, but that looks like a bad response)
Just incase anyone stumbles upon this:
If you have processing.js already loaded, simply call Processing.reload() in your AJAX success/complete function.
Perhaps you already have an element with id="processing" on your page. In that case $("#processing") will only return the first one. If that is the case, change the id or use a class instead.
The other option, which I don't recommend, is to use $("[id=processing]"). That will return every element on the page with id="processing". But, don't use it. Use unique ids in your page, or switch to using classes, whichever works best for you.
Good afternoon all
Here is my scenario:
I have user controls within a master page and within a user control, I may have an update panel. I have the following bit of code I place within a usercontrol that maintains various control styling during partial postback i.e. those controls affected within by an asp update panel.
function pageLoad(sender, args) {
if (args.get_isPartialLoad()) {
$("select, span, input").uniform();
Indeed, when an update panel does its thing, the Fancy Dan styling is maintained.
However, I have one gripe - when a 'large' partial postback occurs, occassionally you'll see the default, generic control styling reappear breifly and then the uniform kicks in to reapply the new fancy styles.
Is there any way I can avoid seeing the nasty old, default, bland stylings?
Any suggestions greatly appreciated.
Check out working with PageManagerRequests: MSDN Working With PageRequestManager
Sys.WebForms.PageLoadingEventArgs Class
Sys.WebForms.PageRequestManager pageLoading Event
$(function() {
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(beautify);
});
function beautify(sender, eventArgs) {
// If we have event args
if (eventArgs != null) {
// for each panel that is being updated, update the html by adding color red
// to select, span, input elements
// must remember to call .html() to put html back into the panelsUpdating[i], otherwise it puts in the jQuery Object
for (var i = 0; i < eventArgs.get_panelsUpdating().length; i++) {
//My test code
//var content = eventArgs._panelsUpdating[i].outerHTML;
//var jContent = $(content);
//$("input", jContent).css("color", "red");
//jContent = $('<div>').append(jContent)
//var jContentToContent = jContent.html();
//alert(jContentToContent);
//eventArgs._panelsUpdating[i].outerHTML = jContentToContent;
//Cleaned up
var jContent = $(eventArgs._panelsUpdating[i].outerHTML);
$("select, span, input", jContent).uniform();
jContent = $('<div>').append(jContent);
eventArgs._panelsUpdating[i].outerHTML = jContent.html();
}
}
}
Edit: I think you understood that the issue was the elements were being placed into the DOM (and therefore painted) before your javascript had a chance to make them uniform(). This intercepts the UpdatePanel and uniform()'s the code prior to it inserted into the DOM
Edit 2 Alright, I've updated it a bunch, I tested this with my test code there and then included the code you're likely to add. Also, I took a short cut in eventArgs._panelsUpdating - i should really be using the get and set functions, but this works.