write html when a href is clicked - javascript

In an unordered list i have some a's with some href's. When clicked I want some html from an external file written. I cannot use any server side languages since it only gonna be running localy.
The structure of my file is:
<body>
<ul>
<li><a href="#">item1</li>
<li><a href="#">item2</li>
<li><a href="#">item3</li>
<li><a href="#">item4</li>
</ul>
<div id="content">
<!-- when a link is clicked write some html from external file to this spot-->
</div>
</body>
</html>
Thanks in advance

Since it looks like you're trying to load a script, there's a better way to do that, by using jQuery.getScript():
$('#triangle').click(function() {
$.getScript("js/triangle.js");
});
Also, as arieljuod points out, you haven't actually loaded jQuery in your HTML file. You'll need to do that to use it:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
(Or pick your favorite jQuery version and CDN; this is one of many.)

You don't want document.write().
You probably want this instead, depending on where you want the new HTML to go:
$('head').append('<script src="js/square.js"></script>');

You can listen for a click on an item and based on that trigger an ajax call for the appropriate file. Load the contents of that file into your content div within the success callback.
Happy to walk you through sample code live over here: https://sudonow.com/session/525cb34035e089113700000a
Pasting the content of the code editor here:
<body>
<ul>
<li id="item1" class="item"><a href="#">item1</li>
<li id="item3" class="item"><a href="#">item2</li>
<li id="item4" class="item"><a href="#">item3</li>
<li id="item5" class="item"><a href="#">item4</li>
</ul>
<div id="content">
<!-- when a link is clicked write some html from external file to this spot-->
</div>
</body>
</html>
//JS
//convert some file content to html
var genHtmlContent = function(content){
//do something here depending on how data is stored e.g. we could just return an html string from some keyvalue json
return content.htmlContent;
}
//Use javascript to detect a click on a list item and grab the appropriate content
$("item").click(function(event){
var selectedId = event.target.id;
var url = "http://www.mysite.com/" + selectedId + ".json";
$.get(url, function(content) {
var htmlContent = genHtmlContent(content);
$("#content").val(htmlContent);
})
})
//sample json file on server
//item1.json
{htmlContent: "<div>I am Item 1</div>"}

A quick and easy solution will be an iframe. Add as many iframes as you want, each having a different url. Give them a common class and hide them using CSS or jQuery. On clicking a link, prevent default and show the corresponding iframe, like;
<ul>
<li><a href="#" id="item1">item1</li>
</ul>
<div id="content">
<iframe class="iframes" id="iframe1" src="http://www.page1.com"></iframe>
</div>
and in your JavaScript, add this;
$('.iframes').hide();
$('#item1').click(function() {
event.preventDefault();
$('#iframe1').show();
});

Related

Side menu with links to parts in Iframes

I've created a webpage that has the following structure:
Main html that uses a side menu;
Secondary html that has the information that I want to show in the main html.
I want to achieve the following. Let's say that the secondary html has a section named intro. I want to link that section to a menu item. So when I press the corresponding button, I want to show in my main html the secondary html starting at the #intro section.
This is my sidebar nav in the main html
<div id="main">
<div class="wrapper">
<!-- LEFT SIDEBAR NAV-->
<aside id="left-sidebar-nav">
<ul id="slide-out" class="side-nav leftside-navigation">
<li class="no-padding">
<ul class="collapsible collapsible-accordion">
<li class="bold"><a class="collapsible-header waves-effect waves-blue active"><i class="mdi-action-view-carousel"></i> Field</a>
<div class="collapsible-body">
<ul>
<li class="active">Intro
</li>
</ul>
</div>
</li>
</ul>
</li>
</aside>
</div>
This is the section in the 2nd html.
<div class="divider"></div>
<div class="section" id="intro">
<li style="list-style: disc">
some text.
</li>
</div>
</div>
When I press the Intro button in the left side nav, I want to open in my main html the 2nd one at the Intro section.
The reason I want to load the 2nd html in my main one is that It uses different css styles and It ruins my formatting if I merge them.
Any solution?
Thank you!
It can be easily achieved with jQuery:
Here's my suggestion:
Step 1
First of all, make sure you have those sections in your secondary.html file:
<div id="intro">Intro section</div>
<div id="section1">Section 1</div>
<div id="section2">Section 2</div>
<div id="section3">Section 3</div>
An, in main.html, make sure you have an element with id=content. This will be your placeholder. Like this:
<div id="content"></div>
Step 2
Modify your anchors:
point href to a dummy url (#).
add a class so we can catch this with jQuery. I named here btn-load-section.
add data- attributes so we can add some useful data to each anchor, to grab it later. I added here data-url and data-section.
Like this:
<li>Intro
<li>Section 1
<li>Section 2
<li>Section 3
Step 3
At the end of our <body> section (in main.html), you can add this code:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
/*
Executes the script inside the anonymous function
only when the page is loaded
*/
$(document).ready(function() {
/*
select all anchors with 'btn-load-section' class (class = dot before)
and bind a click event
*/
$("a.btn-load-section").on("click", function(e) {
e.preventDefault(); //this cancel the original event: the browser stops here
var url = $(this).data('url'); //get the data-url attribute from the anchor
var section = $(this).data('section'); //get the data-section attribute from the anchor
var contentDiv = $("#content"); //select the div with the ID=content (id = hash before). This will be our target div.
/*
executes the jQuery .load function
It will load the url and search for the correspondent section (load page fragment)
e.g. will call load with "secondary.html #intro" (#intro is our fragment on the secondary.html page).
*/
contentDiv.load(url + " #" + section);
});
});
</script>
As I don't know how familiar you're with jQuery, I added some comments.
The first script tag loads jQuery from a CDN.
You can read more about the jQuery's .load function here. But basically it allows to load page fragments:
The .load() method, unlike $.get(), allows us to specify a portion of
the remote document to be inserted. This is achieved with a special
syntax for the url parameter. If one or more space characters are
included in the string, the portion of the string following the first
space is assumed to be a jQuery selector that determines the content
to be loaded.
This is just a possible approach. Hope it helps!

two js function loading in one page

i made a simple website where i have 2 function that loads my pages in menu in one page the problem is when i load one it works ok but when i click on the other same page is load is it not possible to use this kind of function?this is the code
$('#firstcontent1').click(function(){
$('#content1').load('pages/firstcontent1.php');
});
$('#firstcontent2').click(function(){
$('#content1').load('pages/firstcontent2.php');
});
$('#firstcontent3').click(function(){
$('#content1').load('pages/firstcontent3.php');
});
this the HTML
<div id="content1">
</div>
<div >
<ul id="menu-list">
<li id="firstcontent1">firstcontent1
</li>
<li id="firstcontent2">firstcontent2
</li>
<li id="firstcontent3">firstcontent3
</li>
</ul>
</div>
the other is
$('#secondcontent1').click(function(){
$('#content2').load('page/secondcontent1.php');
});
$('#secondcontent2').click(function(){
$('#content2').load('page/secondcontent2.php');
});
$('#secondcontent3').click(function(){
$('#content2').load('page/secondcontent3.php');
});
this is the HTML
<div >
<ul id="menu-list">
<li id="secondcontent1">secondcontent1
</li>
<li id="secondcontent2">secondcontent2
</li>
<li id="secondcontent3">secondcontent3
</li>
</ul>
</div>
<div id="content2" >
</div>
as you can see the id are different and the page name are different as well as the container but for example i load/click id of pages1, content1 will load pages1 and content2 will load page1 as well..i thought when i click on id pages1 content1 will load pages1 but content2 will not load page1 because i did not click the id of page1.
UPDATE:
i notice this only content1 is loaded in content2 for example when i click id pages1 content1 and content2 will load pages1 but when i click pages2 only content2 will load and content1 stays the same meaning the correct page
So your issue might be coming from a typo. You are trying to load the path page/content and pages/content. Not sure if that is just a paste error, but figured I would point that out. Also, it is probably not working because you are using the same id twice -- menu-list. Instead, use a class.
In any event, instead of having 6 different functions, you can consolidate all of this into 1 and then now you can narrow down the issue, if there still is one.
There is also no need to have an <a> tags if you aren't linking it to anything. Instead you are using the jQuery event handlers to capture that click.
This could be the HTML format :
<div id="content1"></div>
<div>
<ul class="menu-list" data="content1">
<li id="firstcontent1">firstcontent1</li>
.
.
.
</ul>
</div>
<div id="content2"></div>
<div>
<ul class="menu-list" data="content2">
<li id="secondcontent1">secondcontent1</li>
.
.
.
</ul>
</div>
Next, your consolidated jQuery should look like this :
$(document).ready(function(){
$('.menu-list li').click(function(){
var content = "#" + $(this).parent().data();
var page = "pages/" + $(this).attr('id') + ".php";
$(content).load(page);
});
});
If you are using jQuery POST version 1.7 your function should like like this:
$(document).on('click', '.menu-list li', function(){
var content = "#" + $(this).parent().data();
var page = "pages/" + $(this).attr('id') + ".php";
$(content).load(page);
});
Now you have yourself a universal function for menu-lists, all you need to do is follow the HTML syntax. As a general programming rule, if you are repeating yourself a lot, chances are you are doing something wrong, or could be doing something better.
EDIT ::
Your issue could be coming from trying to load a page before the last one has completely finished loading.
What happens when you try something like this:
$(document).ready(function(){
$('.menu-list li').click(function(){
var content = "#" + $(this).parent().data();
var page = "pages/" + $(this).attr('id') + ".php";
$(content).load(function(){
$(this).load(page);
});
});
});
Here is an example: FIDDLE
Same as your code. this works.
You have a typo as I mentioned in the comment. You code is fine otherwise, works.
Typo:
page vs pages. Also, make sure your relative path's are working for both pages.
are pages1 and page1 nested, if so the event handle will bubble through both events. Can you try setting
$('#page1').click(function(event){
event.preventDefault();
$('#content2').load('page/page1.php');
});
Try to use live bind:
$('#menu-list').on('click', '#firstcontent1', function(){
$('#content1').load('pages/firstcontent1.php');
});
Tell us what it happened next. =D
Try changing all these:
$('#secondcontent1').click(function(){
$('#content2').load('page/secondcontent1.php');
});
To something like this:
$('#secondcontent1').click(function(event){
event.stopPropagation();
$('#content2').load('page/secondcontent1.php');
});
Add the event.stopPropagation() to each click event and remember to change the function() to function(event).
I think do you want code like this
<div id="content1">
</div>
<div >
<ul class="menu-list">
<li id="firstcontent1">firstcontent1
</li>
<li id="firstcontent2">firstcontent2
</li>
<li id="firstcontent3">firstcontent3
</li>
</ul>
</div>
<div >
<ul class="menu-list">
<li id="secondcontent1">secondcontent1
</li>
<li id="secondcontent2">secondcontent2
</li>
<li id="secondcontent3">secondcontent3
</li>
</ul>
</div>
Then you want the script like this
$('.menu-list li').unbind('click').click(function(){
var id=$(this).attr('id');
var page='pages/'+id+'.php';
$('#content1').load(page);
});
It seems like a cache issue.
Try to use JQuery .ajax, and set no caching for each request:
$.ajax({
url:"pages/firstcontent1.php",success:function(result){
$("#content1").html(result);
},
cache: false
});
In order to see if it's a caching issue / multiple requests per click - run Fiddler and see the exact requests that are being sent - on click.
if you see more than 1 request per click - it means that you're creating multiple requests, instead of a single request - need to fix via "Delegate" & "event.stopPropagation()"
if you see 1 request per click - click again, and see if the response state in Fiddler is 304 OR you don't see the second request at all - if that's the case - use the solution above; or you can gain no-caching with ".load" via
$.ajaxSetup ({
cache: false
});

how to add this class using .append()

I have the following html code:
<nav id="main-navigation">
<ul class="cf">
<li class=" active-link">
Home
</li>
</ul>
</nav>
I need to add the following code before the </ul> tag:
<li class="">
<script type="text/javascript" src="https://app.ecwid.com/script.js?4549118"></script>
<script type="text/javascript">xMinicart("style=","layout=Mini"); </script>
</li>
However, to do so, I have to use jquery's append(). But I don't know the correct way to add the script type="text/javascript", src="https://app.ecwid.com/script.js?4549118"></script> and <script type="text/javascript">xMinicart("style=","layout=Mini"); </script> inside the append().
Thanks!
EDIT 1:
So you can see what I'm trying to do:
what I need is the following http://jsfiddle.net/u3NKD/5/ The results are two links. However, the second link (the one which says "sacola de compras), must be done with append(), not html. That's what I'm trying to do
EDIT 2:
I tried the code in this Jsfiddle http://jsfiddle.net/u3NKD/7/ and it works perfectly in Jsfiddle, but it does not work in my Squarespace website.
The code in my website is the following:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-backstretch/2.0.4/jquery.backstretch.min.js"></script>
<script>
window.onload=function(){
$('nav ul').append('<li id="hello"></li>');
$.getScript("https://app.ecwid.com/script.js?4549118", function(){
xMinicart("style=","layout=Mini","id=hello");
});
}
</script>
Any idea why it doesn't work in squarespace?
Thanks!
Have you tried using something like
$.getScript("https://app.ecwid.com/script.js?4549118", function(){
xMinicart("style=","layout=Mini");
});
to load the script and then activate the xMinicart object afterwards? I can't really understand why you're trying to do this on the fly without more context so that's the best suggestion I can offer.
https://api.jquery.com/jQuery.getScript/ (Load a JavaScript file from the server using a GET HTTP request, then execute it.)
If you really need to place it into that particular spot, then Try this: create a separate html file in the same directory, call it something like myli.html,
then you place this into it:
<ul id="myli">
<li class="">
<script type="text/javascript" src="https://app.ecwid.com/script.js?4549118"></script>
<script type="text/javascript">xMinicart("style=","layout=Mini"); </script>
</li>
</ul>
Then in your original page where you want this appended you do this, you have to create a dummy container like this
$('<div/>', {id:'dummycont', css: {display: 'none'}}).appendTo('body');
then
$('#dummycont').load('myli.html #myli, function(){
var li = $(this).find('#myli').html();
$('nav ul').prepend(li);
});
So basically this load event will load that particular #myli in the myli.html into a temp dummy container. Then you grab grab that content and prepend it to the target ul.
Let me know if that works for you. I havent tested it yet.
What you are doing is that you are just appending the script as a Text or innerText in the HTML DOM structure.
Call the Js using the getScript or Ajax call. (Ajax call with return type script is a getScript)
And in its return function Call the xMinicart function.
In you Dom just Append a 'li' with a specific id and in the getScript success function pass the id to xMinicart function/
<nav id="main-navigation">
<ul class="cf">
<li class=" active-link">
Home
</li>
<li id="hello"></li>
</ul>
</nav>
Your Js call should be
$.getScript("https://app.ecwid.com/script.js?4549118", function(){
xMinicart("style=","layout=Mini","id=hello");
});
This will load the cart on the page.
Check the Jsfiddle here http://jsfiddle.net/u3NKD/6/

Dynamically populating <li> within jQuery Mobile data-role=listview

While using jQuery Mobile <ul data-role="listview">, I am trying to add some <li>s from JavaScript, but the new <li> is not inheriting the jQuery Mobile styles. Here is the code:
<head>
<script>
function init()
{
msg = "<li> <a href=> New List Item </a></li>";
document.querySelector('#add_item').innerHTML += msg;
}
// call init on load
window.addEventListener('load',init,false);
</script>
</head>
<body>
<div id='main' data-role='page' data-theme='c'>
<div data-role='header'>
<h1>Welcome!</h1>
</div>
<div id='content' data-role='content'>
<ul data-role="listview" id="list_cars">
<div id="add_item">
</div>
<li> List Item 1</li>
<li> List Item 1</li>
</ul>
</div>
<div data-role='footer'>
<h4>Enjoy reading the book ...</h4>
</div>
</div> <!-- End of Min page -->
</body>
First, you're putting your <li> inside a <div> instead of directly inside the <ul>. Try changing your querySelector to...
document.querySelector('#list_cars').innerHTML += msg;
or, if you want the item at the top of the list, use this...
document.querySelector('#list_cars').innerHTML = msg + document.querySelector('#list_cars').innerHTML;
Then, you need to tell jQuery Mobile to update that list view by adding...
$('#list_cars').listview('refresh');
The last section on this jQuery Mobile Documentation page about lists describes this feature.
Working example here: http://jsbin.com/omepob/1/
To apply the properties on the new object, the optimal way is to call jQuery's refresh method for the object:
$("#myobject").listview("refresh");
However, I encourage you to replace this innerHTML call for something more DOM-atic, like:
var myli = document.createElement("li");
myli.appendChild(document.createTextElement("List Item 3"));
BTW, agreed with Travis; better include a "ul" as a parent of "li" instead of using a "div" there...

How to change frame source without reloading the page

I am creating a Template Site, i want to change the content of the IFrame
based on the link clicked in javascript,
but the error i get is if i change the 'src' attribute of the iframe
the page gets reload.
So my question is
how to change iframe content without reloading the Page? below is my code
// HTML part
<li class="inside first">
HOME
</li>
<li class="inside">
PRODUCTS
</li>
<li class="inside">
SOLUTIONS
</li>
<li class="inside">
SERVICES
</li>
<li class="inside">
SUPPORT
</li>
<div id="mainContent">
<iframe
src=''
width="100%"
height="100%"
name='content'
id='content'>
</iframe>
</div>
//Javascript part
<script type="text/javascript">
var index=0;
var link_list= new Array('homepage.html','product.html','solution.html',
'services.html','support.html','event.html',
'partner.html','company.html');
var frame=document.getElementById('content');
frame.src=link_list[index];
function clicked(key)
{
// The following line is redirecting the page
frame.src=link_list[key];
return false;
}
</script>
Just write hrefs for those links and add attribute target="content".
This can be done w/o javascript at all.
Your link_list is wrong, JavaScript is case-sensitive, it's new Array(), not new array():
var link_list = new Array(...);
Use the array literal [] and you're fine:
var link_list = ['homepage.html','product.html','solution.html',
'services.html','support.html','event.html',
'partner.html','company.html'];
If you check your browser's JavaScript error console it's easy to find such errors:
[09:16:09.208] array is not defined # file:///.../temp.html:34

Categories