Load partial after clicking link - javascript

On my app I need to dinamically change the main div, where my content is, but at the same time, footer and header are always the same.
The main div are series of handlebars partials create with the help of grunt-handlebars-layouts.
Each div, will change simply clicking on a link.
Untill now my code is very simple:
$( document ).ready(function() {
$('section').on('click', '.next', function(){
moveToNextSection(event);
});
});
function moveToNextSection(event){
event.preventDefault();
var currentSection = event.currentTarget;
var nextSectionId = $(currentSection).find('.next').attr('href');
$(currentSection).closest('section').hide();
// var newSection = find section with nextSectionId as id
// $(newSection).show();
}
home.hbs partial:
<section id="home">
<h2>Welcome Home of {{projectName}}</h2>
<p>I'm the landing and first page </p>
Click here to go to second step
</section>
aborto.hbs parial:
<section id="aborto">
<h1>I'm the second page</h1>
<p>
Sei in cinta e devi abortire? Cerca qui le info necessarie!
</p>
</section>
But I just realize that with my approach, i need all the divs already loaded in the DOM, which I don't have.
Any ideas how to load a hbs partial, when clicking on a link?
Create pre-compiled Handlebars template is my only option here?
Any new approach is welcome :)

Something like this: using jquery load and your code: $(currentSection).find('.next').attr('href') is incorect used in your context :(
<html>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<head>
<title>My First HTML</title>
<meta charset="UTF-8">
</head>
<body>
<section id="home">
<h2>Welcome Home of {{projectName}}</h2>
<p>I'm the landing and first page </p>
Click here to go to second step
</section>
</body>
<script>
$( document ).ready(function() {
$('section').on('click', '.next', function(event){
moveToNextSection(event);
});
});
function moveToNextSection(event){
event.preventDefault();
var currentSection = event.currentTarget;
var nextSectionId = $(currentSection).attr('id');
$(currentSection).closest('section').hide();
var nextPartialUrl = $(currentSection).attr('href');
var wrapper = $('<div id="wrapper"><div></div></div>')
wrapper.load(nextPartialUrl)
$($(currentSection).closest('section')).after(wrapper);
$('#' + nextSectionId).show();
}
</script>
</html>
You need this page accessible: http://www.localhost/aborto.hbs
and returning this
<section id="aborto">
<h1>I'm the second page</h1>
<p>
Sei in cinta e devi abortire? Cerca qui le info necessarie!
</p>
</section>

At the end I decided to go for this solution:
I include all my partials in my index.html
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
{{> home}}
{{> aborto}}
</body>
</html>
Then I hide and show the partials i need with simple js as:
$( document ).ready(function() {
$('section').on('click', '.next', function(){
moveToNextSection(event);
});
});
function moveToNextSection(event){
event.preventDefault();
var currentSection = event.currentTarget;
var nextSectionId = $(currentSection).find('.next').attr('href');
$(currentSection).closest('section').hide();
$('#' + nextSectionId).show();
}
Is probably not the most beautiful solution, since imply adding many partials (now there are just two but the app planning to have 50 partials) but is the one that does what i need for now.
Happy to hear new solutions

Related

How to create an element dynamically in an html page using javascript?

I am learning to create an element dynamically in an html page using javascript. In this code I am trying to create a simple "h6" inside "div-1".
<!DOCTYPE html>
<header>
<meta charset="utf-8">
</header>
<body>
<button onclick="constructElement()">click</button>
<div id="div-1"></div>
<script>
function constructElement(){
var elem = document.createElement("h6");
elem.innerText("Dynamically added text.")
document.getElementById("div-1").appendChild(elem);
}
</script>
</body>
</html>
there are two mistakes in your code
the first is that you used wrong "id" name div-1 instead of div1
also, innerText isn't a function
this is the code after the fix :)
<header>
<meta charset="utf-8">
</header>
<body>
<button onclick="constructElement()">click</button>
<div id="div-1">
</div>
<script>
function constructElement() {
var elem = document.createElement("h6");
elem.innerText = "Dynamically added text."
document.getElementById("div-1").appendChild(elem);
}
</script>
</body>
<header>
<meta charset="utf-8">
</header>
<body>
<button onclick="constructElement()">click</button>
<div id="div-1">
</div>
<script>
function constructElement(){
var elem = document.createElement("h6");
elem.innerText= "Dynamically added text.";
document.getElementById("div-1").appendChild(elem);
}
</script>
</body>
Set the text content of a node: node.innerText = text
function constructElement(){
var elem = document.createElement("h6");
elem.innerText ="Dynamically added text."
document.getElementById("div-1").appendChild(elem);
}
This is directly not your answer but the algorithm is very similar
https://stackoverflow.com/a/56489422/10941112
(For the part of modals please put your own elements)
In case you need further clarification feel free to ask as this is not your direct answer
Also sorry to say but the question is a duplicate of -
Dynamically creating HTML elements using Javascript?

capturing url and loading that urls contents into the same or different div

Wanted to know if it is possible and if so where am i failing on capturing a url and displaying the contents of that file into a div on the same page.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type='text/javascript'
src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'>
</script>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<div data-role="page">
<div data-role="header"></div>
<div data-role="content">
<p id = "heading">Is Nursing For You?</p>
<br/>
<div id = "div1" align="center"></div>
</div>
<div data-role="footer" id = "foot" data-position="fixed">
</div>
</div>
$(document).ready(function() {
$("#div1").load('FONWVhp.php', function() {
$('#div1 div.center-wrapper a button').click(function(event){
event.preventDefault();
($(this).parent().attr('href'));
$("#div1").load(($(this).parent().attr('href'))'articles.php',
function() {
});
});
});
});
</script>
</body>
</html>
fonwvhp.php
index.html loads pages hrefs(which are pointed to articles.php?pageId...)once the page is clicked i want the href to load into the div1 tag and display the href results.
$sqlPAQuery = "SELECT pages.pageId, pages.pageTitle FROM pages order by
pages.pageId";
$paqueryResult = mysqli_query($conn,$sqlPAQuery);
while ($paqueryRow = mysqli_fetch_object($paqueryResult))
{
$pages = "<div class='center-wrapper'><a href = articles.php?
pageId=".$paqueryRow->pageId."><button class= center-
wrapper'>".$paqueryRow-
>pageTitle."</button></a><br/><br/></div>";
echo $pages;
}
articles.php
this is the page i would like to be placed in div1 tag after page href is clicked
$sqlARTICLEQuery = "SELECT * FROM articles where pageId=".$_GET['pageId']."
order by articleId";
$articlequeryResult = mysqli_query($conn,$sqlARTICLEQuery);
while ($articlequeryRow = mysqli_fetch_object($articlequeryResult))
{
$articles ="<div id = 'div1' class='center-wrapper'><a href = article.php?
articleId=".$articlequeryRow->articleId."><button id
='wrapper'>".$articlequeryRow->articleTitle."</button></a><br/><br/></div>";
echo $articles;
}
This is a guess but most likely you forgot the / or you have the ) in the wrong spot
Change
$("#div1").load(($(this).parent().attr('href'))'articles.php'
To
$("#div1").load(($(this).parent().attr('href')+'/articles.php')
These 2 lines
($(this).parent().attr('href'));
$("#div1").load(($(this).parent().attr('href'))'articles.php',
The first line is useless. Delete it.
The second line. You're getting the href of the parent element to the button that was clicked in content loaded from FONWVhp.php (which you didn't post, by the way so I have to guess what it is). To that you are trying but failing to append 'articles.php'.
// Delete me ($(this).parent().attr('href'));
$("#div1").load($(this).parent().attr('href') + 'articles.php',
Note that this will work fine as long as the href always ends in a slash. If it doesn't, which might be likely (depending again on what the mysterious FONWVhp.php contains) then you will have to figure that out too (by putting a slash in, most likely).

jQuery mobile - get the loaded page ID?

I have a document called "info.html".
it have 5 pages:
food
toys
entertainment
smartphones
electronics
I want that once a page loads, jquery send a request to the server for information about this item.
I all need to know is how to trigger this function?
Tried:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>CoCouppn!</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"></script>
<script type="text/javascript">
$(document).on("pageshow", function() {
alert($(this).attr('id'));
});
</script>
</head>
<body>
<div data-role="page" class="pge" id="food">
food
</div>
<div data-role="page" class="pge" id="toys">
toys
</div>
<div data-role="page" class="pge" id="entertainment">
entertainment
</div>
<div data-role="page" class="pge" id="smartphones">
smartphones
</div>
<div data-role="page" clsas="pge" id="electronics">
electronics
</div>
</body>
</html>
It alerts "undifined" instead of page ID.
What is the problem?
Note that pageshow is deprecated in jQuery Mobile 1.4: http://api.jquerymobile.com/pageshow/
Note also that $.mobile.activePage is deprecated.
If you want to get the active page ID, you can do:
$.mobile.pageContainer.pagecontainer( 'getActivePage' ).attr( 'id' );
or
$('body').pagecontainer( 'getActivePage' ).attr( 'id' );
or
$(':mobile-pagecontainer').pagecontainer( 'getActivePage' ).attr( 'id' );
I do not personally recommend the latter two, as you are free to set a different pagecontainer, which in fact I do in Jasmine tests.
Note that the page must really be active first (it is not active yet in pagecreate, for instance).
pagechange event and retrieve page's id from data object.
$(document).on("pagechange", function (e, data) {
var page = data.toPage[0].id;
});
Demo
pageshow:
$(document).on("pageshow", function (e, data) {
var page = $(this)[0].activeElement.id;
});
Demo
You can get the current page information in a shorter and clearer way:
$(".ui-page-active").attr("id")
This is just a variation from the code shown here: http://demos.jquerymobile.com/1.4.5/toolbar-fixed-persistent/#&ui-state=dialog
Try $(document).ready( function ), $(document).ready allows you to execute a code in jQuery only when the page is loaded.
If you want to use pagecreate event, use this.id
$(document).on(
"pagecreate",
'#page_1, #page_2',
function(event) {
var pageId = this.id;
...
}
);

Dynamically adding collapsible set and nested list in jQuery mobile

I am adding a listview inside a collapsible dynamically. And inside that list I am trying to add a nested list. When I am clicking the <li> node, pageinit event is getting fired instead of click event. The click event is getting fired when we click the same li second time.
jsFiddle - http://jsfiddle.net/5zJC5/
HTML:
<body>
<div data-role="page">
<div data-role="collapsible-set" data-theme="b" data-content-theme="d" id="mainColl"></div>
</div>
</body>
jQuery:
$(document).ready(function () {
var ul=$("#mainColl");
var collapsible= $('<div data-role="collapsible">');
collapsible.append('<h2>Collapsible</h2>');
var list = $('<ul data-role="listview" data-divider-theme="b">');
list.append('<li data-role="list-divider">List</li>');
for(var j =0;j<4;j++) {
list.append("<li>Item</li>");
}
collapsible.append(list);
ul.append(collapsible);
ul.trigger('create');
});
$("#mainColl").on("click","li",function() {
var list = $("<ul>");
for(var i=0;i<4;i++) {
list.append("<li>test</li>");
}
$(this).append(list);
//$(this).trigger('create');
$(this).parent().listview('refresh');
});
You have to use list.append("<li>Item</li>"); instead of list.append("<li>Item</li>");.
Updated jSFiddle here.
In addition, note that is is not recommended to use the document ready handler in combination with jQuery Mobile. I would suggest to add an id on the jQM page and use an event handler of the 'pagebeforeshow' event.
$(document).on('pagebeforeshow', '#page-id', function(){...mycode...});
You can find a jsFiddle which includes the suggested fix here
At last I would like to suggest you to avoid creating dynamic parts like that. You will realize that after some time your code will become messy and hard to read.
My proposal is to use Undescore.js as a template engine and make your code reusable and clean.
EDITED to add handler on nested list items:
<!DOCTYPE html>
<html>
<head>
<title>jQuery Mobile Nested List</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
<script>
$(document).on('pagebeforeshow', '#home-page', function ()
{
var collapsibleSet=$("#mainColl");
var collapsible= $('<div data-role="collapsible"></div>');
collapsible.append('<h2>Collapsible</h2>');
var list = $('<ul data-role="listview" data-divider-theme="b"></ul>');
list.append('<li data-role="list-divider">List</li>');
for(var j =0;j<4;j++)
{
list.append("<li>Item</li>");
}
collapsible.append(list);
collapsibleSet.append(collapsible);
collapsibleSet.trigger('create');
});
$(document).on("click","#mainColl li",function()
{
var list = $("<ul id=\"second-list\"></ul>");
for(var i=0; i<4; i++)
{
var listItem = $("<li id=\"list-" + i + "\">Test</li>").on('click', function(){alert(this.id)})
list.append(listItem);
}
$(this).append(list);
$(this).parent().listview('refresh');
});
</script>
</head>
<body>
<div data-role="page" id="home-page">
<div data-role="content">
<div data-role="collapsible-set" data-theme="b" data-content-theme="d" id="mainColl">
</div>
</div>
</div>
</body>
</html>
I hope this helps.

Adding style to Header when div is clicked using Javascript

My intent is to add a class to the header when a div is clicked. I have included the website I'm working with, just to make thing's easier:
URL - http://itsmontoya.com/work/iM/
I have added a class 'expanded' to the header. This is to show how the navigation should look after the button has been pressed. I created a simple Javascript which is supposed to provide an alert when I click the button. I can't seem to get this to work. Any ideas of what I did wrong?
Thanks!
EDIT - I was able to get the alert to properly work when clicking the button div. I'm very close to having this complete! :) Now I'm getting stuck with the variable not passing correctly.
<script type= "text/javascript">
var expanded = false;
function btnClick(){
alert('The variable expanded is '+expanded);
if(expanded === false) {
document.getElementById("header").className = "expanded";
var expanded = true;
} else {
document.getElementById("header").className.replace(/\bexpanded\b/,'');
var expanded = false;
}
};
</script>
I'm updating the ftp server now :)
When using jQuery, you have to bind your events in such a way that the elements have already loaded.
You have:
<script type= "text/javascript">
$("#expandBtn").click(function(){
alert('hello');
});
</script>
I think what you want is:
<script type= "text/javascript">
$(document).ready(function(){
$("#expandBtn").click(function(){
alert('hello');
$('header').addClass('expanded');
});
});
</script>
The API documentation is going to be your friend here. First step -- ready().
UPDATE
You have this call to jQuery:
$j('#header').addClass('expanded');
But your markup is for the HTML5 element <header>. In that case your jQuery needs to change to:
$j('header').addClass('expanded');
Where $j is your jQuery object. More typically you would use $ or jQuery.
Time to bone up on jQuery Selectors!
UPDATE
Here's your updated page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>itsMontoya</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="shortcut icon" href="/favicon.ico" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type= "text/javascript">
$(document).ready(function(){
$('.expandBtn').bind('click', function(){
$('header').toggleClass('expanded');
});
});
</script>
</head>
<body>
<div class="wrap">
<header id="header" class="">
<div class="blackBG transparent"></div>
<nav>
<ul>
<li>
Home<img src="images/home.png">
</li>
<li>
Pictures<img src="images/pictures.png">
</li>
<li>
Music<img src="images/mymusic.png">
</li>
<li>
About Me<img src="images/aboutme.png">
</li>
<li>
Resume<img src="images/resume.png">
</li>
</ul>
</nav>
<div id="logo" class="logo"><p>itsMontoya</p></div><div id="expandBtn" class="expandBtn anchor"></div>
</header>
<section class="content">
<article class="blogEntry"></article>
</section>
<footer class="anchor">
<div class="over anchor"><p>2011 itsMontoya.com</p></div>
<div class="blackBG transparent anchor under"></div>
</footer>
</div>
</body>
</html>
Using jQuery:
$('#your_div_id').click(function(){
console.log("Clicked.");
$("#header").addClass('expanded');
});
Update
In your code:
var expanded = false;
function btnClick(test){
if($expanded === false) {
.
.
.
What the heck is $expanded? Notice that in JavaScript we don't need the $ sign for variables.
This is how you would bind a click handler to your div and add the class to your header:
var yourDiv = document.getElementById('your-div-id');
var header = document.getElementById('header');
yourDiv.onclick = function(){
alert("yourDiv was clicked");
header.className = "newCssClass";
};
The above assumes markup like so:
<div id="your-div-id">Click</div>
<div id="header"></div>
Here's an example.
Update: The reason that the expanded variable isn't working as you'd expect is because you're creating a duplicate local variable called expanded in your btnClick() method. As a result, the global expanded variable you declare outside the function is never updated.
This is being caused by how you're using the var keyword:
When used outside a function, var creates a global variable that's accessible anywhere within the current document.
When used inside a function var creates a local variable that is accessible only within that function.
Here's your function cleaned up to work as you'd expect:
// Define global variable (using var outside function)
var expanded = true;
function btnClick(){
alert('The variable expanded is '+expanded);
// Condition for true
if(expanded) {
// do something
// Condition for false
} else {
// do something else
}
// Flips boolean value of the global variable (notice lack of var keyword)
expanded = !expanded;
}
Here's an example showing the correct way to update the expanded variable.

Categories