footer HTML inside Javascript - footer

Hello i'm using the following javascript code which will be in a separate file so that it can be referenced globally across the site.
It allows me to have a global reference for html elements such as footers and menus and include them by id:
<body>
<div id="copyright"></div>
<script>
var copyright = document.getElementById("copyright");
copyright.innerHTML = "<p>© Some Company 2013</p>";
</script>
</body>
This works ok as long as the javascript is placed at the bottom of the page. I was wondering what i might need to modify to allow me to move the script into the header?
Many thanks.

Run the code on DOM ready. Not fun without a library like jQuery, but I have to ask why you're doing this at all.
There are far, far better ways to reuse HTML: templating.
Okay, so you're using jQuery. Then you can use the usual, pervasive document ready handling:
$(document).ready(function ()
{
$('#copyright').html('<p>© Some Company 2013</p>');
});
// or the short-hand version
$(function ()
{
$('#copyright').html('<p>© Some Company 2013</p>');
});
That said, I still recommend templating instead. You can even do it client-side, with jQuery.

Related

What is #section scripts and what it is used for

I have downloaded a chat example from the Microsoft website. I have been following several tutorials but I have never seen the #section script{} before I have done scripts without this block of c# code (#section script{}) and it seem to work fine but in this instance of the chat application using signal R when I do take the scripts outside the block it does not work.
#section scripts {
<!--Script references. -->
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
}
A section allows you to add something in a view which will be added in the layout. ie:-
view
#section scripts {
<script>
alert('foo');
</script>
}
layout
#RenderSection("scripts", false)
now this named section scripts will be rendered where you have specified in the layout.
#RenderSection also has 2 signatures:-
public HelperResult RenderSection(string name) // section required in the view
public HelperResult RenderSection(string name, bool required)
When you define an #section somewhere, lets say the _Layout.cshmtl file, it allows all of your Views to dynamically insert script files or CSS files or what ever into places in the defining page.
This is very nice when, for example, you are using the jQuery UI Datepicker control only on a couple views in your site. So you may not want to globally include the jQuery UI Datepicker script file in your _Layout.cshtml since you are only going to need it on 2 or 3 pages.
#section allows you to include those files only for certain views. It is needed since, a view cannot easily change the contents of the _Layout.cshtml otherwise.
You can also position the #section at the bottom of the layout, for JavaScript files for example, or at the top of the layout, for CSS files. You could also use it to include a sidebar, made in HTML, only in certain views.
Just be aware that Partial Views are not able to use the #section element by default.
There is also one thing that should be added to the answers above that makes the use of "scripts" section crucial in most cases which is also the only reason for me to use this section.
That is, it guarantees that scripts will load after all page contents which is essential. By doing this, you actually make sure necessary elements for your JavaScript code have loaded already and also it is a matter of performance.
To elaborate how it works, I should mention that:
That is a common practice to put the commonly used scripts inside the "_Layout" page to make them accessible among all pages and also prevent their repetition.
All contents of child views are loaded into the _Layout view where #RenderBody() method is called. Except the contents inside #sections of each view.
When we define "scripts" section inside the footer of the layout for common scripts and then add our scripts of child views inside the "scripts" section of each child view we make sure that these scripts will load after the script of the layout that makes the functions in the _Layout available to the scripts of the child views.
Otherwise, the scripts of child views would be loaded where RenderBody() method is called, before the common scripts of the _Layout page.
For Example:
Inside _Layout:
#RenderBody()
<footer>
<script>
$(function CommonlyUsedFunction() {
console.log("text");
});
</script>
#RenderSection("Scripts", required: false)
</footer>
Inside MyView:
<script>
CommonlyUsedFunction(); //Function is not Accessible Here
//It will not be accessible because RenderBody() will load the function before its declaration.
</script>
#section Scripts
{
<script>
CommonlyUsedFunction(); //Function is Accessible Here
</script>
}
I'd just like to add another form of answer here, because it took me a combo of reading all three current answers and some experimenting before I understood it.
I copied some ajax code for a modal popup that was enclosed in #section scripts { } and put it in a view. It worked fine, but I took away the section bit, because it was encapsulated in <script> html - which is normally fine;
My view before:
#Section scripts {
<script> ... my function ... </script>
}
<h1>The rest of the page</h1>
How I normally include a one-off script on a view:
<script> ... my function ... </script>
<h1>The rest of the page</h1>
By doing this, the script is rendered inside the html of the view itself and the popup stopped working. This is because the script accesses elements outside of that view - it needs site-wide access so to be able to stop using #section scripts I would have to be put in the layout file.
But I only really want this script rendered when this view is being used. I don't want to put it in the _layout file and have it loading on every single page.
Lucky me! At the bottom of a default _layout file there's a line (I normally remove, to be honest):
#RenderSection("scripts", required: false)
So by enclosing my <script>s in #section scripts { } on any view, it becomes part of the _layout, and is loaded after all other content (it's right at the bottom of the layout page), but only when that particular view is used.
It basically allows a dynamic layout page which is very clever, I wonder if it's possible to do with stylesheets too.

MVC HTML helper wrapper for jqPlot

I wish to create an MVC wrapper around jqPlot.
I want to have a helper object to render the required html container element and the required java scripts to draw the chart.
Something that will look like this:
#Html.jqPlot()
.ChartType(eChartTypes.PieChart)
.ChartData(someData)
.RenderChart();
Now I'm only at the initial design phase and I know what the jqPlot object should look like to achieve that, the problem I'm having is with the java script that suppose to be emitted to draw the actual chart using jqPlot.
Suppose I will render the following script in my .RenderChart() method
public string RenderChart()
{
string chartCode = string.format(#"
<script type="text/javascript" src="../src/plugins/jqplot.canvasTextRenderer.min.js"></script>
<script type="text/javascript" src="../src/plugins/jqplot.canvasAxisLabelRenderer.min.js"></script>
$(document).ready(function(){
var plot1 = $.jqplot ('{0}', [{1}]);
});
",this.ChartGuid, this.ChartData);
return chartCode;
}
The above is not actual code but just a general representation of the idea.
So the problem is that i don't want the Helper to emit the JS code into the body of the Html document, furthermore i cannot let it do that becuse some of the required scripts may be at the bottom of the html (as the best practice states).
Any suggestions ?
What would be the best way to emit JS code using an HTML helper if the situation requires it (like this one) ?
I think, listening to an even will be a possible solution, in this case the even of outputting or finishing the rendering of the footer. so maybe your code will give as an option to listen to an event and render at that moment, but this is of course platform dependent. I also worked on a php wrapper you can fork it here: https://github.com/oumsofiane1/jqplotPHPwrapper.git
and just implemented a helper, but of course you can extend that :-)
Hope this helps

Emberjs and jQuery UI integration questions

I am trying to understand how the integration between jQueryUI and Emberjs should be done. I am new to both libs and to javascript so this might be a newbie question.
I have this jsfiddle set up: http://jsfiddle.net/pSKgV/1/ and it renders this resulting document:
<body class="ember-application">
<div id="ember129" class="ember-view">
<div id="ember163" class="ember-view ui-draggable"></div>
</div>
</body>
The code is mostly taken from this blog post: http://www.lukemelia.com/blog/archives/2012/03/10/using-ember-js-with-jquery-ui/
Questions: How do I put something inside the inner div? I want to put some content that i can bind to something.
I have tried the following:
{{view App.Draggable}}Drag Me{{/view}} but that gives an error. I’ve also tried
adding this to the App.Draggable object:
didInsertElement: function() {
this.$().html(“Drag Me”)
}
but that did not give the expected results. How is the best way to use/access the jquery/jqueryui functions such as .html() in this situation?
Also, is the outer div necessary or can I make this view only render one div element?
regards
Oskar
http://jsfiddle.net/ud3323/XMgwV/
You forget the # symbol {{#view App.Draggable}}Drag me{{/view}}. You should also create namespaces in Ember using Ember.Namespace.create() instead of just using an empty {}

How to use pageinit correctly?

I have a single file for each page and i am trying to implement the pageinit event handler on every page (I think what belongs strictly to one page, should be declared there) as shown below:
<body>
<div id="myPage" data-role="page">
<!-- Content here -->
<script type="text/javascript">
$("#myPage").live('pageinit', function() {
// do something here...
});
</script>
</div>
</body>
The event is bound properly to the page, so the code is executed but - now my problem - if i go to another page and return later on the pageinit event will be executed twice. I think that is because the .live method binds the pageinit event again to the page. But shouldn't the pageinit event only called once at page initialization? What I am missing here?
I solve the issue by passing the name of the event, in this case the "pageinit" instead of the handler.
<script defer="defer" type="text/javascript">
var supplier = null;
$("#pageID").die("pageinit"); //<--- this is the fix
$("#pageID").live("pageinit", function(event){
console.log("initialized - #(ViewBag.ID)");
supplier = new Tradie.Supplier();
supplier.Initialize("#(ViewBag.ID)");
});
Ref: http://www.rodcerrada.com/post/2012/04/26/jQuery-Mobile-Pageinit-Fires-More-Than-Once.aspx
I think its probably best to move your JavaScript code into another file as while your navigating around your site jQuery Mobile may cleanup (read: delete from DOM) that myPage page and therefore will have to load it in again and hense rerun that same block of code you defined and bind 2 listeners for the pageinit event.
Thats basically why they suggest using the live or on functions however it falls over if you include the binding code on the page ;)
However if you insist on having your code placed on a per page basis than use bind instead of live.
Ref: http://jquerymobile.com/demos/1.0/docs/pages/page-cache.html
jQuery Mobile therefore has a simple mechanism to keep the DOM tidy. Whenever it loads a page via Ajax, jQuery Mobile flags the page to be removed from the DOM when you navigate away from it later (technically, on the pagehide event).
I'm pretty sure they recommend binding pageinit to the document using on(). E.g.
$(document).on ('pageinit', '#myPage', function (event) {
instead of having the pageinit bound to the page, which is getting re-inited. In fact, I thought $(document).on() was the recommended way to bind events in jQuery, in general, now.
A quick workaround I have used is declaring a variable containing the handler function.
var handler = function() {
// your code
};
Then always use die() before binding the handler with live()
$( "#myPage" ).die( handler ).live( handler );
I'm sure this is not the intended usage by the authors, but it does the trick, you can leave your code within the page DIV.
$("#page1").live("pageinit", function () {
alert('pageinit');
$("#page1").die("pageinit"); //<--- prevent from firing twice on refresh
});

How to open a link from a Joomla article into the same article window

I'm trying to have the users click on the links in an article, but have the results open in the same article (so the article reloads and open the target page in itself, like it would if it was in an iframe, right now it reloads the whole page), I do not want to use the main menu, and would also like to avoid using iframes, normally if this was HTML I'd use ajax or something similar, but in joomla i'm not sure, any suggestions?
If you have HTML ids you are better of using AJAX, Joomla has jquery and mootols to make your life easier.
There are couple of things you should know
Look into JUMI, it will allow you to use PHP within your articles. Can be very helpful. You can use it to add javascript framework from article for your ajax like so <?php JHTML::_('behavior.mootools'); ?>
You want to be careful while editing the article, if you use editor it will strip out your JavaScript from the article. You are better of just using "No-Editor" or if you are using JCE switch to text by pressing "Show/Hide" just above the editor in the left corner.
Add events to your IDs in domready instead of inline js. Something like this
/* MooTools Example */
window.addEvent('domready', function(){
$('link-1').addEvent('click', function(){ new Ajax(...).request(); });
$('link-2').addEvent('click', function(){ new Ajax(...).request(); });
$('link-3').addEvent('click', function(){ new Ajax(...).request(); });
});

Resources