Create link with JQuery - javascript

I got this Jquery code
<head>
<script type="text/javascript">
$(document).ready(function() {
$("#pav li a").click(function() {
$(".srvctext").empty().append("<div id='loading'><img src='loading2.gif' alt='Loading' /></div>");
$("#pav li a").css('color','#656565');
$(this).css('color','#3ca5d4');
$.ajax({
url: this.href,
success: function(html) {
$(".srvctext").empty().append(html);
}
});
return false;
});
});
</script>
</head>
and this HTML
<div class="srvclinksholder">
<h4> Our Services </h4>
<ul id="pav">
<li>Technical Infrastructure Service</li>
<li>Email Exchange Service (Messaging)</li>
<li>Firewall Services</li>
<li>Security and Antivirus Service</li>
....
I want to be able create a link from another page to one of these pages, I think I have to use # somehow just unsure. So if I have <a href="service/pages/page_4.html"> service being the page name that will not obviously work. Maybe something like this <a href="service.html#pages/page_4.html">
What changes do I have to make to achieve this?

DEMO: http://jsfiddle.net/LxreN/3/
Basically you are going to be changing the html of the other div.
$(".srvctext").html("<div id='loading'><img src='loading2.gif' alt='Loading' /></div>");
with the following the in success, there isn't a need to empty everytime since that is causing 2 DOM accesses everytime, which IE doesn't handle well.
success: function(html) {
$(".srvctext").html(html);
}

Related

Jquery load method conflict current script with child page external script

I have a free template with dashboard menu and the main content section. I want that when a user clicks on menu link and the child page will be loaded into the main content section. I don't want to user embed tag or iframe because of some problems so I tried Jquery load method and $.ajax.
The problem is the menu included 2 external scripts (bootstrap and jquery); when child page loaded, they didn't understand scripts of the menu. But if I put 2 more same scripts tag to child page or using $.getScript(), the child page loaded but jquery.js and bootstrap.js were seemed to be conflicted and worked on the wrong way.
main code
<html>
<head>// Some css link</head>
<body>
<!-- Menu -->
<div class="menu">
<ul class="list">
<li class="header">MAIN NAVIGATION</li>
<li class="active">
<a href="index.html">
<i class="material-icons">home</i>
<span>Home</span>
</a>
</li>
<li>
<a href="javascript:void(0);" onclick="setPage('child.jsp')">
<i class="material-icons">text_fields</i>
<span>Child page</span>
</a>
</li>
</ul>
</div>
<section class="content" id="main-content">
</section>
<!-- Jquery Core Js -->
<script src="plugins/jquery/jquery.min.js"></script>
<!--Bootstrap Core Js-->
<script src="plugins/bootstrap/js/bootstrap.js"></script>
<!-- Select Plugin Js -->
<script src="plugins/bootstrap-select/js/bootstrap-select.js"></script>
<script>
function setPage(page) {
$.ajax({
url: page,
}).done(function (data) {
$("#main-content").html(data);
// $.getScript("plugins/jquery/jquery.min.js");
// $.getScript("plugins/bootstrap/js/bootstrap.js");
// $.getScript("plugins/bootstrap-select/js/bootstrap-select.js");
// $.getScript("plugins/jquery-countto/jquery.countTo.js")
});
}
</script>
</body>
child code
<div class="info-box bg-pink hover-expand-effect">
<div class="icon">
<i class="material-icons">playlist_add_check</i>
</div>
<div class="content">
<div class="text">NEW TASKS</div>
<div class="number count-to" data-from="0" data-to="125" data-speed="15" data-fresh-interval="20"></div>
</div>
</div>
If I run without $.getScript, child page loaded into section but just content and css, js didn't work. If I run with $.getScript ( or put external script inside child page) ,child page loaded with js but jquery and bootstrapsjs go wrong with some unexpected animation.
Thanks guys so much.
Once you have jQuery on the page (and bootstrap) no need to add those back in. Getting content that does contain script will execute once it is on the page. Notice I put a small bit to add a class to the menu, and it executes when loaded.
Here I "fake" the ajax using a jQuery Deferred - jQuery .ajax() returns a deferred so it really can be a good fake for that.
Note I commented out the console.log() to make this example cleaner but you can uncomment to see them to see what is there at each step.
Note just for clarity jQuery
$.getScript(myurl);
is an alias for
$.ajax({
url: myurl,
dataType: "script",
success: success
});
SO, given that I added a fake ajax for an independent script also.
// this is fake ajax content
var ccode = '<div class="info-box bg-pink hover-expand-effect"><div class="icon"><i class="material-icons">playlist_add_check</i></div><div class="content"><div class="text">NEW TASKS</div><div class="number count-to" data-from="0" data-to="125" data-speed="15" data-fresh-interval="20"></div></div></div><scr';
ccode += 'ipt>$(".menu").addClass("showAction")</scr';
ccode += 'ipt>';
// this is fake script content
var fakeScript = '<scr' + 'ipt>$("#main-content").addClass("showScriptLoaded")</scr';
fakeScript += 'ipt>';
// this is fake script content
var otherFakeScript = '<scr' + 'ipt>console.log("proof"+$(".goodchild").text());$(".goodchild").append(" says Howdy!");</scr';
otherFakeScript += 'ipt>';
// just for the demo, think of this as ajax
function getFakeAjax(deferred) {
//console.log('in fake ajax');
deferred.then(function(data) {
//console.log('fake stuff then');
return data;
})
.done(function(data) {
//console.log('fake ajax data', data);
$("#main-content").html(data);
// kick off fakescript load
var def2 = $.Deferred(getFakeScript);
// pass that fake ajax object
def2.resolve(fakeScript);
})
.fail(function() {});
}
// just for the demo, think of this as getScript
function getFakeScript(deferred2) {
//console.log('in fake ajax');
deferred2.then(function(data) {
//console.log('fake stuff then');
return data;
})
.done(function(data) {
if (jQuery) {
// jQuery is loaded
alert("Yeah! well duh we just used it");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
//console.log('fake ajazx script', data);
$(data).appendTo("#main-content");
})
.fail(function() {});
}
function setPage(page) {
//console.log('setPage', page);
// I used the fake for this
// $.ajax({
// url: page,
// }).done(function(data) {
// $("#main-content").html(data);
// });
// call the fake the ajax
var def = $.Deferred(getFakeAjax);
// fax ajax done (second one)
def.done(function(data) {
// pretend our server is slow to load first script
// 4 seconds later kick off second fakescript load
setTimeout(function() {
var def2 = $.Deferred(getFakeScript);
// pass that fake ajax object
def2.resolve(otherFakeScript);
}, 4000);
})
// pass that fake ajax object
def.resolve(ccode);
}
.showAction {
border: solid lime 2px;
}
.showScriptLoaded {
border: solid red 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap-theme.css" rel="stylesheet" />
<body>
<div class="menu">
<ul class="list">
<li class="header">MAIN NAVIGATION</li>
<li class="active">
<a href="index.html">
<i class="material-icons">home</i>
<span>Home</span>
</a>
</li>
<li>
<a href="javascript:void(0);" onclick="setPage('child.jsp')">
<i class="material-icons">text_fields</i>
<span class="goodchild">Child page</span>
</a>
</li>
</ul>
</div>
<section class="content" id="main-content">get content here
</section>
</body>

Scrape a page with Javascript and then append a specific section to current page

I'm trying to scrape and then pull out a specific section (section-two) to append to my current page.
Current page
<div id="container">
</div>
<script type="text/javascript">
$.ajax({
url: "external.html",
dataType: 'text',
success: function(data) {
var externalPage = data;
$("#container").append(externalPage);
}
});
</script>
external.html
<div class="section-one">
<p>Content I don't want</p>
</div>
<div class="section-two">
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</div>
Ideal Result
<div id="container">
<div class="section-two">
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</div>
</div>
So far I have loaded the external page into a variable but I do not know how to filter out only the section I want to append. Can anyone help me out? Thanks in advance.
To only append .section-two, you'll need this:
$.ajax({
url: "external.html",
dataType: 'text',
success: function(data) {
var externalPage = $($.parseHTML($.trim(data)));
$("#container").append(externalPage.find('.section-two'));
}
});
$.trim() (optional) will remove any newlines and spaces at the beginning and end that might be in external.html. $.parseHTML() will convert the HTML string to a set of DOM nodes (so that we can traverse it). The surrounding $ will convert the DOM nodes to a jQuery object so that we can use .find() method to filter out the descendant that we want.
Try this
$.ajax({
url:"template.html",
dataType:'text',
success:function(data){
var parsedHTML=$.parseHTML($.trim(data));
var arr= jQuery.grep(parsedHTML, function( node, index ) {
if($(node).attr('class')=="section-two"){
return node;
}
});
$("#container").append(arr[0]);
}
});

jQuery ToDo list

I work on the simple ToDo list written on jQuery (and JS, of course).
I already created the static ToDo list with a possibility to add new items only by editing the code. It is logically that I am going to create a dynamic list now.
I've already tried some methods, like .load() code from external file, create .after(), but it all goes wrong for me.
What would you suggest me to do?
You may find all the source codes in strasbourgmeetings.org/ccc
I would be very grateful if you could help me solving this question.
Gloserio, yes, Add Item does not work now, because I of the problem I described.
ncubica, the problem is that at the moment I am not able to add new items to my list (only bu editing the code). Dynamic means that it would be possible to add/delete items. To do that I tried to use .after() method with the function inside it, that will copy the <li id="item1">List item here</li><li id="buttons1">Buttons here</li> (roughly speaking), but it puts all list items on the upper side and all buttons to the bottom.
This is a part of the JS code:
<script>
// Waiting for the document to load
$(document).ready(function() {
// Wanted to create a dynamic item list, that's why I used this variable. I thought it would
// generate unique IDs (there was 'id++' somewhere in the function I already deleted).
var id = 1;
// This is going to be used as an action for 'Add Item' button. (It is not a button, actually, it is just <span> with cursor: pointer. Using <a> causes page reload);
$('.add').click(function() {
$('#item'+id).after(function(i) { // '#item'+id should be something like this in the code: #item2, #item3, etc.
})
})
// 'Done' button
$('#done1').click(function() {
console.log('# "Done" button pressed');
$('#list1').css('background-color','#89f49a').css('border','1px solid #16bf31').css('text-decoration','line-through').css('color','#817f7f').css('font-weight','normal');
console.log('# Item doned successfully');
});
// 'Undone' button (is gonna be renamed to 'Reset');
$('#undone1').click(function() {
console.log('# "Undone" button pressed');
$('#list1').css('background-color','').css('border','').css('text-decoration','').css('color','').css('font-weight','normal');
});
// 'Working' button
$('#working1').click(function() {
$('#list1').css('background-color','#edc951').css('border','1px solid #dda119').css('font-weight','bold').css('color','#000').css('text-decoration','none');
});
// 'Cancel' button
$('#cancel1').click(function() {
$('#list1').css('background-color','#ff8c8c').css('border','1px solid #ea2c2c').css('font-weight','normal').css('text-decoration','line-through').css('color','#f00');
});
// 'Delete' button
$('#del1').click(function() {
$('div#dlist1').remove();
$('li#action1').remove();
});
});
</script>
And HTML part:
<div class="list">
<ul id="sortable">
<div class="list-item" id="item1"><div class="spacer1" id="spacer1"></div>
<div class="l-element" id="dlist1"><li id="list1" class="ui-widget ui-state-default">Create add feature</div>
<li id="action1" class="action"><input type="button" value="Done" class="done" id="done1"><input type="button" value="Undone" class="undone" id="undone1"><input type="button" value="Working" class="working" id="working1"><input type="button" value="Cancel" class="cancel" id="cancel1"><span id="del1" class="delete">Delete</span></li>
<div class="spacer"></div></div>
</ul>
<div>
As you can see, there is only 1 list item I wrote. IDs are static and can not be changed at the moment. All I need is to change IDs (ok, it will be var id = 1; id++) and to add the part of the code (inside <div class="list-item")
why don't you try jQuery's .clone() and attach it to the "Add Item" behaviour?
You can check it here.
I personally made one as well, and it works really simply, a checkbox, the text, followed by a delete button.
Works great, though I'm still working on a way to make it save it after you close the browser.
jQuery code:
function addListItem() {
var textToAdd = $('#new-text').val(); // The finish class is just for css styling
$('#list').append('<li class="item"><input type="checkbox" class="finish" />' + textToAdd + '<button class="delete">Delete</button></li>');
$('#new-text').val('');
}
function deleteItem() {
$(this).parent().remove();
}
$(document).ready(function() {
$('#add').on('click', addListItem);
$(document).on('click', '.delete', deleteItem);
});
HTML code:
<!DOCTYPE html>
<html>
<head>
<title>To Do List</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h2>To Do List</h2>
<p>Project started on <strong>4-1-2015</strong>.</p>
<input type="text" id="new-text" /><button id="add">Add</button>
<ul id="list">
</ul>
<script src="jquery.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
Hope this helped :)

What is the technique to dynamically build out collapsible data sets in jQuery Mobile

I can only assume that what I am trying to do is a very common requirement when working with dynamic javascript applications.
For this particular example, I want to request detailed test results via JSON. So for some users they might have done 20 tests, others might have done 1. Some users might have got 2 questions wrong in a particular test which will get referenced, others might have got 10 questions wrong, some got 0. Only the questions that are wrong would get displayed.
So in other words I am requesting a different layout for a collapsible data set upon each user who requests it.
The static code might look something like this:
<div data-role="collapsible-set" data-theme="b" data-content-theme="d">
<div data-role="collapsible">
<h2>Test Number 2 - 2 out of 5 correct</h2>
<ul data-role="listview" data-theme="d" data-divider-theme="d">
<li data-role="list-divider">You did not complete the following:</li>
<li><h3>A (answer is: X)</h3></li>
<li><h3>B (answer is: Y)</h3></li>
<li><h3>C (answer is: Z)</h3></li>
</ul>
</div>
<div data-role="collapsible">
<h2>Test Number 1 - 4 out of 5 correct</h2>
<ul data-role="listview" data-theme="d" data-divider-theme="d">
<li data-role="list-divider">You did not complete the following:</li>
<li><h3>A (answer is: X)</h3></li>
</ul>
</div>
</div>
As somebody who is relatively new to JavaScript and jQuery I am still getting the hang of this, I have played around with some DOM manipulation in the past. Just wondered if there is another name for what I am trying to accomplish, and maybe even a library, pre-built code that I can use floating around GitHub, etc that does something like this without me having to build everything from scratch. Want to do this the right way.
You don't need a special framework for this, everything you need is already a part of jQuery.
I have created an example for you: http://jsfiddle.net/Gajotres/HBxTs/
HTML :
<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="width=device-width"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<div data-role="page" id="index">
<div data-role="content">
<div data-role="collapsible-set" data-theme="b" data-content-theme="d">
<div data-role="collapsible">
<h2>Simple list</h2>
<ul data-role="listview" data-inset="true" id="movie-data" data-theme="a">
</ul>
</div>
</div>
</div>
</div>
</body>
</html>
JS :
$('#index').live('pagebeforeshow',function(e,data){
$.ajax({url: "http://api.themoviedb.org/2.1/Movie.search/en/json/23afca60ebf72f8d88cdcae2c4f31866/The Goonies",
dataType: "jsonp",
jsonpCallback: 'successCallback',
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
success: function (result) {
ajax.parseJSONP(result);
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
});
var ajax = {
parseJSONP:function(result){
//var jsonObj = jQuery.parseJSON(parameters);
$('#movie-data').append('<li>Movie name:<span> ' + result[0].original_name+ '</span></li>');
$('#movie-data').append('<li>Popularity:<span> ' + result[0].popularity + '</span></li>');
$('#movie-data').append('<li>Rating:<span> ' + result[0].rating+ '</span></li>');
$('#movie-data').append('<li>Overview:<span> ' + result[0].overview+ '</span></li>');
$('#movie-data').append('<li>Released:<span> ' + result[0].released+ '</span></li>');
$('#movie-data').listview('refresh');
}
}
Only thing you need to take care is to execute this function after content has been added:
$('#movie-data').listview('refresh');
It is used for listview restyling.

Programmatic (as opposed to link-based) navigation in jQueryMobile

The problem has been discussed several times, but I am yet to see a concrete answer.
Similar/same question : SO question
Suppose that I have index.html:
<div id="index1" data-role="page">
<div data-role="header"><h1>Index 1</h1></div>
<div data-role="content"></div>
<div data-role="footer">
<a data-role="button" id="toshop2">
To Shop 2
</a>
</div>
</div>
and shop.html:
<div id="shop1" data-role="page">
<div data-role="header"><h1>Shop 1</h1></div>
<div data-role="content"></div>
<div data-role="footer">
<a data-role="button" href="#shop2">To Shop 2</a>
<a data-role="button" href="index.html" rel="external">
To Index
</a>
</div>
</div>
<div id="shop2" data-role="page">
<div data-role="header"><h1>Shop 2</h1></div>
<div data-role="content"></div>
<div data-role="footer">
<a data-role="button" href="#shop1">To Shop 1</a>
<a data-role="button" href="index.html" rel="external">
To Index
</a>
</div>
</div>
and I want to do something like:
$('#toshop2').on('click', function() {
$.mobile.changePage("shop.html#shop2");
});
which, as we all know by now, won't work. It'll grab the first DOM page (#shop1 out of shop.html and append it into index.html DOM.
I know that something silly like:
$('#toshop2').on('click', function() {
window.open('shop.html#shop2', '_parent');
});
would work (yes, there won't be a transition).
Questions are (assuming there is no other solution, but to hack):
Can I/should I hack it differently?
Can I somehow still get transition to an external page?
You can request the external document manually and then only insert the portion that you want to the DOM:
//delegate event handler binding to links with a custom class
//(any link that links to a pseudo-page in an external document
$(document).delegate('.my-external-links', 'click', function () {
//get the location of the external document and the requested page (hash)
var theHREF = this.href,
theTarget = '#shop1';
if (theHREF.indexOf('#') > -1) {
theTarget = '#' + theHREF.split('#')[1];
theHREF = theHREF.split('#')[0];
}
//first see if this page is already in the DOM, if so just navigate to it
if ($(theTarget).length) {
$.mobile.changePage($(theTarget));
return;
}
//show the loading spinner
$.mobile.showPageLoadingMsg();
//do AJAX request to get new pages into the DOM
$.ajax({
url : theHREF,
success : function (response) {
//hide the loading spinner
$.mobile.hidePageLoadingMsg();
//find all the `data-role="page"` elements and add them to the DOM
$(response).find('[data-role="page"]').appendTo('body');
//now navigate to the requested page which should be in the DOM
$.mobile.changePage($(theTarget));
},
error : function (jqXHR, textStatus, errorThrown) { /*don't forget to handle errors*/ }
});
return false;
});
I'm pretty sure there is a plugin for this as well, but as you can see it's not that much code or complication.
why don't you try to use changepage twice?
$.mobile.changePage( "shop.html", { transition: "none"} );
$.mobile.changePage( "#shop2", { transition: "slideup"} );
or just use loadPage to load the shop.html into DOM in background and change to #shop2 after?
$.mobile.loadPage( "shop.html" );
$.mobile.changePage( "#shop2", { transition: "slideup"} );

Categories