Change CSS on AJAX request in Wicket - ajax

I have a component A that should dynamically change the font size of some of it's contents. I currently use CSS variables to do that and the component will contribute some CSS String containing these CSS variables:
public void renderHead(IHeaderResponse response) {
String fontCss = // dynamically fetch CSS cariables
response.render(CssHeaderItem.forCSS(fontCss, "font-css"));
}
On the same page I have the possibility to change these font sizes using an AJAX update within another component B. This will add the component A to the AjaxRequestTarget, which will cause the renderHead method to be executed with updated values for the font CSS variables.
However, I don't see an updated font size in my browser as the old CSS variables still seem to be present. How can I enforce the new CSS to overwrite the old one?
So far I found 2 solutions, that seem like dirty workarounds to me:
Add the whole page to the AjaxRequestTarget, so the whole page will be refreshed.
Add JavaScript to the AJAX update to remove the old styling with:
var allStyles = document.getElementsByTagName("style");
for (var style of allStyles) {
if (style.getAttribute("id").includes("font-css")) {
style.remove();
}
}
Is there a cleaner solution to this problem?

You found the problem with workaround 2.
response.render(CssHeaderItem.forCSS(fontCss, "font-css"));
adds <style id="font-css"> ... </style> to the page. Later when the Ajax response contributes the new content the JavaScript logic finds that there is an HTML element with id font-css and assumes that there is nothing to do.
A simple solution is to use dynamic id, e.g. by using UUID in #renderHead().
Another solution is to make this <style> a proper Wicket Component, a Label, that could be added to the AjaxRequestTarget with an updated Model when needed.

Related

Could not show content in CKeditor after the second time

In my project, the Ckeditor is part of a webpage, which is coded using GWT. So the interface to CKeditor is using Java.
Whenever the webpage is displayed, the CKeditor will be passed a HTML via setData(), which the CKeditor is supposed to show.
The problem is: CKeditor sometimes won't show the HTML. Its content was just empty, although I am very sure the html had been passed to setData().
I had tried several approaches to solve this problem, but none would work.
My approach
Create a TextArea using DOM.createTextArea()
Call myEditor=CKEDITOR.replace(textArea, config) to initialize the CKeditor
call myEditor.setData(html) to set the content.
It was good and showed the content at the first time.
But after the webpage got hidden and shown again, I called myEditor.setData(html2) to show another html, but this time the CKeditor showed nothing.
First solution (did not work)
I changed the code to call myEditor.destroy() before the webpage was hidden, and call CKEDITOR.replace(textArea, config) again when the webpage was visible again, after that I called myEditor.setData(newHtml).
This time it worked in IE and FF, but not in Chrome and Edge, it kept showing the content of the first load time, instead of showing the new HTML.
Second solution (did not work)
I changed it to call CKEDITOR.inline(textArea, config) instead of CKEDITOR.replace(textArea, config) when the webpage was visible again, while the destroy() and setData() was still called in the same order. This time the CKeditor again didn't show anything from the second time.
Last attempt
My last approach was to not calling destroy(), but creating a new TextArea each time before showing CKeditor, and called CKEDITOR.replace(textArea, config) and setData(html). This seems to work well, but occasionally the CKeditor still showed empty content.
Could anyone please help me to solve this problem?
I am using CKeditor 4.5.8.
Finally I figured out the solution:
Before hiding the ckeditor, call editor.destroy(true), and delete editor. (Before this, I only called editor.destroy() [note: no 'true'], which didn't work well).
Here is the code:
if (editor) {
editor.destroy(true);
delete editor;
}
Use this java script code that is very simple and effective.Note editor1 is my textarea id
<script>
$(function () {
CKEDITOR.timestamp= new Date();
CKEDITOR.replace('editor1');
});
</script>
second way ! In controller ,when your query is fetch data from database then use this code after .success(function().
$http.get(url).success(function(){
CKEDITOR.replace('editor1');
});

Reload javascript after thymeleaf fragment render

I have javascript files defined in the <head> of both my layout decorator template and my individual pages which are decorated. When I update a thymeleaf fragment in one of my pages the javascript defined in the head of the parent page no longer works. Is there a standard way to 'refresh' these js files?
Thanks.
Additional clarification :
I have a form submitted by an ajax call which updates a table in the page. I have a Jquery onClick function targeting a button in the updated table. The javascript doesn't seem able to bind to the returned elements in the updated part of the page. I select by element class and can see that the selection works prior to the partial fragment render.
For me it is unclear what you mean by
javascript defined in the head of the parent page no longer works.
The page is created on the server. Normally it contains urls of the javascript files
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
In this case 'refreshing' the javascript files can happen only in the client.
Check the html of the page in the client.
Are the tags as expected ?
Are there tags for all expected javascript files ?
With the browser tools (for example Google Chrom developer tools ) check that all script files are actually loaded.
If this doesnt help, it could be that the order of the script tags has changed between the first and second load. This could cause a different behaviour of the javascript executed in the browser.
EDIT :
With the initial load you bind javascript callbacks to dom elements.
You do this directly or through Jquery or other libraries.
When a new dom element is loaded, it has no callbacks bound to it, even if it has the same id as a replaced dom element.
So after the load you have to bind your callbacks again.
If you bound them 'by hand', just bind it again.
If you are using a JQuery plugin, that made the bindings, look into the code or documentation, many of them have a function for that or you can call initialization again.
Once you added new content to the DOM you need to bind again the new content.
Let's say I have a button with some class, the event in binded to the class:
<button class="someclass">Button 1</button>
<script>
var something = function() {
// do something
};
$(".someclass").on("click", something);
</script>
If I add more buttons from the same class to the DOM, they will have not have the click event binded. So once you load the new content via ajax, also remove all binding and add again (you need to remove or you will have buttons with 2 events).
$(".someclass").off("click");
$(".someclass").on("click" , something);

Single page application with Rails 4 and AngularJS

Ok, this idea might seem quite a bit crazy and it kindo' is (at least for me at my level).
I have a fairly standarad rails app (some content pages, a blog, a news block, some authentication). And I want to make it into a single page app.
What I want to accomplish is:
All the pages are fetched through AJAX like when using turbolinks, except that the AJAX returns only the view part (the yield part in the layout) withought the layout itself, which stays the same (less data in the responces, quicker render and load time).
The pages are mostly just static html with AngularJS markup so not much to process.
All the actual data is loaded separately through JSON and populated in the view.
Also the url and the page title get changed accordingly.
I've been thinking about this concept for quite a while and I just can't seem to come up with a solution. At this point I've got to some ideas on how this actualy might be done along with some problems I can't pass. Any ideas or solutions are greatly appreciated. Or might be I've just gone crazy and 3 small requests to load a page are worse then I big that needs all the rendering done on server side.
So, here's my idea and known problems.
When user first visits the app, the view template with angular markup is rendered regularly and the second request comes from the Angular Resource.
Then on ngClick on any link that adress is sent to ngInclude of the content wrapper.
How do I bind that onClick on any link and how can I exclude certain links from that bind (e.g. links to external authentication services)?
How do I tell the server not to render the layout if the request is comming from Angular? I though about adding a parameter to the request, but there might be a better idea.
When ngInclude gets the requested template, it fires the ngInit functions of the controllers (usually a single one) in that template and gets the data from the server as JSON (along with the proper page title).
Angular populates the template with the received data, sets the browser url to the url of the link and sets the page title to what it just got.
How do I change the page title and the page url? The title can be changed using jQuery, but is there a way through Angular itself?
Again, I keep thinking about some kind of animation to make this change more fancy.
Profit!
So. What do you guys think?
OK, in case enyone ever finds this idea worth thinking about.
The key can be solved as follows.
Server-side decision of whether to render the view or not.
Use a param in the ngInclude and set the layout: false in the controller if that param is present.
Have not found an easier way.
Client-side binding all links except those that have a particular class no-ajax
Here's a directive that does it.
App.directive('allClicks', function($parse) {
return {
restrict: 'A',
transclude: true,
replace: true,
link: function(scope, element, attrs) {
var $a = element.find('a').not($('a.no-ajax')),
fn = $parse(attrs['allLinks']);
$a.on('click', function(event) {
event.preventDefault();
scope.$apply(function() {
var $this = angular.element(event.target);
fn(scope, {
$event: event,
$href: $this.attr('href'),
$link: $this
});
});
});
}
};
})
And then use it on some wrapper div or body tag like <body ng-controller="WrapperCtrl" all-links="ajaxLink($href)"> and then in your content div do <div id="content" ng-include="current_page_template">
In your angular controller set the current_page template to the document.URL and implement that ajaxLink function.
$scope.ajaxLink = function(path) {
$scope.current_page_template = path+"?nolayout=true";
}
And then when you get your JSON with your data from the server don't forget to use history.pushState to set the url line and document.title = to setr the title.

Is it possible to use razor syntax in Javascript files?

I'd like to use razor syntax inside my Javascript files. Is this possible without including the javascript inline into the page?
I found a razor engine RazorJS on nuget that solves # in js files
The owner blog and explanations about the package abilities
The Nuget package
see more in this question
The Razor engine only runs against the page, not any included javascript files.
You could write a custom parser that will run the view engine against any javascript files before serving them, and I imagine any attempt to do so would be a very useful open source project.
However, the simplest solution that comes to mind (if these variables are not sematically linked to any DOM elements) is to simply declare and initialise your variables in the page (or in an included partial page) and your javascript (in .js files) relies on these variables being defined.
If however the variables that you require are logically associated with DOM elements, I prefer to use data-* attributes to define these, this way your javascript can be consumed by the html, rather than the other way around. For example, if you have a content area that should be automatically updated by javascript (using jQuery as an example here):
HTML:
<div data-auto-refresh="pathToContent" data-auto-refresh-milliseconds="1000"></div>
Javascript:
$(function() {
$('[data-auto-refresh]').each(function() {
var self = $(this);
var url = self.data('auto-refresh');
var interval = self.data('auto-refresh-milliseconds');
// Code to handle refresh here ...
});
});
You can set the value in hidden field in yout cshtml file , and then in your javascript files you can access the hidden field.

Stylesheet for tooltip in firefox extension

I've developed a Firefox extension for displaying explanations for some unusual words. My problem is that my tooltip get's modified by other stylesheets of the current page. So on some pages my stylesheet looks fine and on some it's totally messed up. Is there a way to limit my stylesheet to my tooltip notes so that stylesheets from the webpage wouldn't affect mine?
I'm loading my stylesheet that way:
initTooltipStyle: function(on) {
var sss = Cc["#mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);
var uri = makeURI("resource://tooltip/tooltip.css");
if (sss.sheetRegistered(uri, sss.USER_SHEET))
sss.unregisterSheet(uri, sss.USER_SHEET);
if (on)
sss.loadAndRegisterSheet(uri, sss.USER_SHEET);
},
I have experienced this problem. Most of the time the style property which you didn't applied to your element will be easily overriden by webpages. For instance, if you didn't declare margin for your div element and webpage has declared div{margin:0;} your element will also inherit it. Try adding reset.css to your elemets(http://meyerweb.com/eric/tools/css/reset/).
Then try adding your elements into the root elemnt of the page instead of body. document.documentElement.appendChild(). These techniques helped me.
Hope that helps!

Resources