Basic jQuery on hyperlink clicked print content - javascript

I was hoping for a little guidance if possible. On my website I have a small area that shows "Most Popular" and underneath I have 4 hyperlinks: Blogs, Tips, News, Videos. I want it so that if the user clicks the hyperlink it prints the appropriate content below, ideally without loading the entire page but not essential.
I'm new to jQuery so if someone could help me that would be super.
Thank you.

Have a look at jQuery's AJAX, especially the load method: http://api.jquery.com/load/
In a nutshell, this method makes a request to a URL, and writes the response into any element you specify. In your case, I would likely:
1) Create a URL which returns the HTML snippet you want to display e.g:
<div><p>Popular Blog 1</p><p>Popular Blog 2</p></div>
2) In the javascript on your page, add something like this:
$("a#myPopularBlogsLink").click(function() {
$("#loadAndReplaceContentInThisElement").load("http://mywebsite.com/some-url-returning-data/);
});
3) If you read through the jQuery docs, you may be able to adapt this better to your situation - for example, passing a parameter in the .load() method to choose which page you want to load data for, etc.
It's hard to say what the best practice would be without more details on your situation - how much flexibility you have server-side with URLs, how much control you have over your content, and if you need search engines to index the content (they will NOT index content loaded through AJAX).

Using jQuery, you could try something like this:
<script type="text/javascript">
$(document).ready(function() {
$("#alink").click(function () {
$("#aframe").attr("src", $(this).attr('href'));
return false;
});
});
</script>
<a id="alink" href="http://www.google.com">Google</a>
<div id="adiv">
<iframe id="aframe" src="" width="100%" height="300"></iframe>
</div>

Related

How to use Javascript to change href and html text?

So I've got this little piece of HTML that I have zero access to, and I need to change the URL of where it's linking, to somewhere else.
Now I've looked around, and I've tried different approaches and non seem to work so I must be doing something wrong.
the Html code:
<div class="manageable-content" data-container="edit_register_ind_container">
<a class="entry-text-link secondary-step step-button" id="register_ind_container" href="oldurl">Register</a>
</div>
First I wanted to try something that seemed easier, which was to change the displayed text "Register" to "Start a Fundraiser"
This is what I have got for that part:
// url manipulation
$(document).ready(function(){
$("#register_ind_container").click(function(){
$("#manageable-content a").text('Start a Fundraiser');
});
$("#register_ind_container").attr("href", "http://google.ca");
});
No luck so far for any of it.
a little background information:
I am using a platform called Luminate/Blackbaud, its a CMS with a weird set up. header tags and stuff like that go in a different place than the html body and the css is somewhere else as well (but I'm just using ftp to reference it in the header).
How I'm referencing the javascript code.
<script type="text/javascript" src="../mResonsive/js/urlmanipulation.js"></script>
My css works so I'm certain this should to, but I just don't know why it isn't.
All suggestions welcome (except for asking for the html access because I have, 3 weeks ago lol)
Thank you for your time!
I saw your both code :
$("#register_ind_container").attr("href", "http://google.ca");
This line will execute on page load so href should be changed on load
$("#register_ind_container").click(function(){
But when you performing this click on Id
it wont work because at that instance this id associated with an hyperlink
so hyperlink having the default subset rules
for Overriding this you can try
$("#register_ind_container").click(function(e){
// custom handling here
e.preventDefault();
$(this).text('Start a Fundraiser');
});
But this is also not a Good Practice. Hope this helps !
$(document).ready(function(){
$("#register_ind_container").click(function(){
$(this).text('Start a Fundraiser');
$(this).attr("href", "http://google.ca");
});
});
You are changing the URL outside the click event.. Wrap it inside the click event.. Also make use of $(this)
// url manipulation
$(document).ready(function(){
$("#register_ind_container").click(function(){
$(this).text('Start a Fundraiser').attr("href", "http://google.ca");
});
});

Click on nav-element loads/includes new content/file.php into div id="include"

I'm looking for the best (fast, does not need a lot of performance, easy to understand, et cetera) method of loading some content from a php-file into a div of my page.
I don't know if it's better to use php or javascript maybe? If javascript, I think there is no need for jquery, right?
The solution should be 100% valid (w3c, jshint, et cetera).
On first page load: should some specific includes-file be loaded, or just nothing but the original content of my div should be shown?
There should be no reload of the whole page, just the div should be reloaded / the content of the div should be replaced when clicking on the navigation-link.
(It should not matter, what the files which are loaded/included are named so I don't want a solution which does only load files with the names file_1.php ... file_9.php.)
The files also just have plain html in it, like if I would write it directly into the div of my html-file.
The files which should be included are e.g. called about.php, contact.php, services.php…
My html/php file looks like this:
<html>
</html>
<body>
<div id="container">
<div id="nav">
<ul>
<li>...</li>
<li>...</li>
<li>...</li>
</ul>
</div>
<div id="content">
<div id="include">
</div>
</div>
</div>
</body>
The best way to lead the content in div in my opinion is using jQuery.
It will be compatible with major browsers, and simple to implement.
Actually I use this solution in one of mine apps
$(document).on('click', '#nav a', function(event) {
var url = $(this).attr('href');
$.ajax(url).done(function(response, status) {
if (status !== "error")
{
$("#include").html(response);
}
});
event.preventDefault();
});
Explaining:
$(document).on('event', 'filter', handler) is a function that bind a handler function to every 'event' filtered by 'filter'.
(More info at jQuery Documentation .on())
Inner the handler, I use a jQuery function called .ajax(), that receives a url as parameter (and some options if necessary), and call a callback function using defered.done().
This callback receives response data, status string and the xhr object as described in jQuery documentation. (In this case we do not use the xhr object, then we can remove it from function)
First I check if status is not a error. Then I select the '#include' element (jQuery uses a css like selector syntax), and use html function to put the response inner #include div.
For last, i use event.preventDefault() to avoid browser from trying to follow the link.
However, if you want to use pure JavaScript, you will need to handle different browsers behavior, and you will take a long time to get 100% compatible.

reccommended way to output HTML from JavaScript

I know this has probably been asked before, but here goes: I have a web application that needs to generate modal dialogs. alert, confirm, and prompt are too simple and ugly, and that modal window function...it's a long story. I can't use it. So, I'm going to create the modal box using DOM functions and CSS. However, I need to put quite a lot of content into the dialog, and I'm wondering what the best way to do this is. Putting the HTML into a string and using innerHTML is unwieldy. I could use the DOM, but that's annoying and takes too much time to code. I know I can use a script with a weird type tag (something like x-random/x-htmlstuff) and then copy it's content to the innerHTML, but is there a better, more "official" way to do this?
if the layout of the modals are static, just put them into the HTML of the page. Use CSS to set them to display: none when the page is displayed normally. When you want to display the model, use
document.getElementById('modal-id').style.display = 'block';
I've heard that some people use this solution:
<script type="text/html" id="popup_html">
html...
</script>
(of course, you should make it invisible)
But, most likely, if you're trying to write a lot of HTML from javascript, then you should retrace and think if there's a better way.
If you're using the same div multiple times, you should just create it in the HTML page, and display it when needed
if you're creating a new element - see if you can use the document.createElement and appendChild methods (assuming there aren't many nodes involved)
if neither apply - retrace. For large projects, maybe object-oriented javascript can help.
There's no magical way that I'm aware of. I usually just use innerHTML and write the HTML out in a well formatting from such as:
box.innerHTML = "<div id='boxChild'>\n" +
" <p>Put whatever content here</p>\n" +
"</div>";
The \n make it so if you view your code, it will be well formatted, and no one long string once the JS writes it.
A way to do this, is to generate the popups within the html and show or hide them when you need, like this:
<div class="myPopup">
<div class="pop-message msg-01">This a pre generated alert with the id: <span class="dynamic-field-01"></span></div>
<div class="pop-message msg-02">This another pre generated alert with the id: <span class="dynamic-field-02"></span></div>
<div class="pop-message msg-03">...</div>
</div>
.pop-message {
display: none;
}
Now while user navigates the page, you are going to hide and show the .pop-message's while replacing those .dynamic-field's if needed.
I would suggest having the HTML for your modal content in separate files, and then loading it asynchronously when you need it to popup the modal.
partials/modal.html
<div class="content">My modal content</div>
main.js
var modalContent = null;
function _fillModal() {
modal.innerHTML = modalContent; // something like this
}
function openModal() {
if (!modalContent) {
// XMLHttpRequest, which populates the modalContent variable
// and in the callback, calls _fillModal()
}
// If already filled, just call
_fillModal()
}
If you want the content to be dynamic, make modal.html a template, and use a JS template library (for example http://underscorejs.org/#template), or write a simple RegExp replace yourself.
I'd suggest loading it with innerHTML or using jQuery to simplify things, but if you need
a modal window, could you use the jQuery UI modal dialog, shown here?
If you have the content loaded in divs in your HTML, and have them have css display:none;, and then show them with
document.getElementById("unshown-div").style.display="block";
If you can use jQuery, a modal box could be done with
<div id="modal" style="display:hidden">
Here is a modal dialog bbox
</div>
and your script:
$("#dialog").dialog();
Whatever you do, just don't use document.write()

Static content in website

I've got a website and I'd like to make a part of it static. What happens is that the header, the menu bar and the footer are consistent in every page. I'd like to have them always loaded and when I click the menu button, it will only reload what is the body of the site.
Is there a simple chunck of code that can early achieve this? Something in js or ajax? I'm sorry but I don't have enough experience in these languages to accomplish something on my own. I've already tried to check jQuery library but it's still pretty confusing to me.
Thank you.
I think you don't even need Ajax or css!! Just use iFrames!! They are awesome, what happens is that u only design one page as the holder of your static content (Header-Menu ...) and put one iFrame in there as a place holder for any page you want to load in it, u should use proper css code to place the iFrame where you want, now, for every link in your menu, just set the "target" attribute equal to your iFrame's name and all the links will be loaded in that iFrame and your page won't be reloaded with every link click... I'll be back with some code...
Just add in every page a div container with ID for header, menubar and footer and just load it with this:
$(document).ready(function(){
$('#header').load('header.html');
$('#menubar').load('menubar.html');
$('#footer').load('footer.html');
});
Just make sure that the html files don't have html, head or body tags within, only the HTML-Code you would write inside the div. It's just like the include function in PHP.
EDIT:
For easy and simple implementation store the code above inside a .js file (e.g. include.js) and add this inside every head just below the include of all other scripts of your html files:
<script type="text/javascript" src="include.js"></script>
EDIT2:
Another solution ist to load the content of the page instead of the header, menubar, footer.
Here you take the same specifications (no html, body, etc. tags inside your content html files)
Name your content div e.g. <div id="content"></div>
Your navbar for example:
<div id="navbar">
Content1
Content2
</div>
JavaScript Code:
$(document).ready(function() {
//Click on a link that's child of the navbar
$('#navbar > a').click(function() {
//Get the html file (e.g. content1.html)
var file = $(this).attr('href');
//Load this file into the #content
$('#content').load(file);
return false;
});
});
You should consider the use of Server Side Included : http://httpd.apache.org/docs/current/howto/ssi.html
It's not quite easy to understand (as it refer to apache configuration), but this is a really great solution.
In a nutshell, you include parts of html code in you main page :
<!--#include virtual="/footer.html" -->
You won't have to use or understand all JQuery Framewol, user agent won't have to parse (if they are able to !) Javascript.
This is a pretty good replacement of PHP / ASP / Java for this kind of purpose.
You could use ajax to request the body of each page. But this is only one possibility - there are many. An other approach could be to create you page content using a script language (php, perl) serverside and employ a function there which adds footer, header and anything else to each page.
If you have an idea of Jquery then use click event on menu links to load the page in a div like the following syntax may help you.
$(document).ready(function(){
$("a.menu").click(function(){
$("#bodyContent").load("http://abc.com/your-linked-page.html");
});
});
To load the url dynamically use the following code:
In your menu bar the link looks like:
Home
In your Jquery code:
$(document).ready(function(){
$("a.menu").click(function(){
url = $(this).attr("title"); // here url is just a variable
$("#bodyContent").load(url);
});
});
Step 1: Add Jquery file into your html page.
Step 2: Use the above jquery code and change your menu link to the new what i said here.
Step 3: If you done it correctly, It will work for you.
How about a traditional iframe?
In your menu:
<a target="body" href="URL_to_your_Menu1_page">Menu1</a>
and then further in the document:
<iframe name="body" src="URL_to_homepage"></iframe>
You may use frameset and frames and organize you pages accordingly. So, frames containing menus can always be at display and while displaying contents on click of menu u may set target to frame in which you would like to load the contents.

Change div content with link in another div

i have a menu bar with links which are in the header. when you click the link, i want to just change the content in the main div. i'm thinking of doing it in php, but you will have to reload the page. So i need to do it in javascript, but i dont know javascript.
here is my menu code in the header div:
<ul id="nav">
<li>Enter Information</li>
<li>View Records</li>
<li>View Upcoming</li>
</ul>
If you think about using PHP, I guess that you have to load dynamic content. For this, I advice you to use AJAX
The easiest is to use a framework, like the famous Jquery. Example here
here i am assuming that you get your content with a function call as content()
var list=document.getElementById('nav');
var links=list.getElementsByTagName('a');
var header=document.getElementById('header');
for (var i=0;i<links.length;i++)
{
links[i].onclick=function() {
header.innerHTML=content(); //here you can use something else to generate the content
}
}
You want to use jquery to build something like this. If you are serious about building web apps you need to learn how to use it (or a similiar framework like MooTools)
For this particular problem I would use an existing menuing system, here's the first list of jquery based menus that I found, but there are many more.
You don't need any anchor elements. W3 example
<script>
$(document).ready(function() {
$('.menu').click(function() {
$("div").load('somecontent.txt');
});
});
</script>
<ul>
<li class="menu">Enter Information</li>
<li class="menu">View Records</li>
<li class="menu">View Upcoming</li>
</ul>
Depending on the type of content, you have a few options available to you. If you need to load a new page into the main content, you can use iframes and some javascript. If you need to load simple text, you can simply use javascript.
Based on your feedback, you'll do something like this (note- I'm shooting from the hip regarding syntax, but this is generally what your code will need to look like):
Link 1
<iframe id="MainContent">
</iframe>
<script>
function UpdateIFrame( newPageAddress ){
document.getElementById("MainContent").contentWindow.location = newPageAddress;
}
</script>
In order to dynamicly load content (e.g. from a server using php/sql) without having to reload the website Ajax is exactly what you need.
Inlineframes (mentioned before), however, should not be used for they are deprecated.
W3schools provides a very basic but straightforward tutorial on Ajax.

Categories