I have div class="contentBlock" which is treated as the container for updating
<div class="contentBlock"></div>
I have a script that I wrote that doesnt work :c
$(document).ready(function(){
$('.postLink').on('click', function () {
$.get("page.php", function (data) {
$(".contentBlock").html(data);
});
});
});
I have a anchor html
<div class="box">
<a class="postLink" "href="#">
<h1 title="Light me up"></h1>
<div class="innerbox">
<figure><img src="http://cpsr-rspc.hc-sc.gc.ca/PR-RP/servlet/ShowImage?photoId=1789" /></figure>
<ul class="categorySelect">
<li class="print"></li>
<li class="video"></li>
<li class="web"></li>
</ul>
</div>
</a>
</div>
The page.php is just an img tag amd some lorem.
I've never worked with .get() I'm sure I'm using it incorrectly. Additionally, where would I add a transition for a loading .gif and a fadein when loaded?
<a class="postLink" "href="#">
Should be
<a class="postLink" href="#">
You had an extra quote.
$(document).ready(function(){
$(".postLink").on('click', function () {
// load in animation.gif here
$(".contentBlock").load("page.php", function() {
// end loading animation now
});
});
});
Using a load in jQuery is meant for exactly this purpose.
Here's the jQuery doc for load: http://api.jquery.com/load/
Related
I want to trigger the click on a tag which has div with id='a'.
$(document).ready(function() {
$("#chat_list_content a:has(div[id='a'])").click();
//$("#chat_list_content a:has(div[id='a'])").trigger("click");
$('#chat_list_content a').click(function() {
alert('you are here');
})
})
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<div id="chat_list_content">
<a href="#">
<div id="a">A</div>
</a>
<a href="#">
<div id="b">B</div>
</a>
</div>
Click should happen automatically and output alert box. But, there is no respond from the code.
Thanks in advance.
When you call $("#chat_list_content a:has(div[id='a'])").click(), the custom click handler is not yet described yet. That means it doesn't do anything. You just need to move the click trigger below the click function definition:
$(document).ready(function() {
//$("#chat_list_content a:has(div[id='a'])").trigger("click");
$("#chat_list_content a").click(function() {
alert("you are here");
});
// Make sure to add this after the click handler definition above
$("#chat_list_content a:has(div[id='a'])").click();
});
working sandbox: https://codesandbox.io/s/exciting-gagarin-t55er
There is no need to use :has() here at all, you can simply use Attribute Equals Selector [name="value"] to achieve what you are looking for.
$(document).ready(function(){
$('#chat_list_content a').click(function(){
alert('you are here at '+ $(this).index());
});
$('#chat_list_content a div[id=a]').click();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chat_list_content">
<a href="#">
<div id="a">A</div>
</a>
<a href="#">
<div id="b">B</div>
</a>
</div>
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>
I need some help. As you will see in my fiddle, I am attempting to use buttons to populate a single container div with content from multiple hidden divs, depending on which button is clicked. The problem I am having is, I don't know how to access the actual content in the hidden divs to populate the container div. As of now, I am using the id attributes for the hidden divs to demonstrate which div content I would like to display in the container.
I've seen a few other posts with link <a> attributes referencing hidden content, but none so far using a button element with click functionality to change div content.
jQuery(function ($) {
$('#button1').click(function () {
$('#info').empty();
$('#info').prepend('#option1');
});
$('#button2').click(function () {
$('#info').empty();
$('#info').prepend('#option2');
});
$('#button3').click(function () {
$('#info').empty();
$('#info').prepend('#option3');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button-panel">
<ul id="button-column" style="list-style: none;">
<li class="buttons"><button id="button1">Button 1</button></li>
<li class="buttons"><button id="button2">Button 2</button></li>
<li class="buttons"><button id="button3">Button 3</button></li>
</ul>
</div>
<div id="info-div">
<div id="info"></div>
</div>
<div id="hiddenDivs" style="display:none;">
<div class="info" id="option1">Box</div>
<div class="info" id="option2">Google Drive</div>
<div class="info" id="option3">Box</div>
</div>
Here is my fiddle
Here's a version that uses jquery data attributes. It reduces the redundancy and complexity and can be configured easily.
<body>
<div class="button-panel">
<ul id="button-column" style="list-style: none;">
<li class="buttons"><button id="button1" data-link="option1">Button 1</button></li>
<li class="buttons"><button id="button2" data-link="option2">Button 2</button></li>
<li class="buttons"><button id="button3" data-link="option3">Button 3</button></li>
</ul>
</div>
<div id="info-div">
<div id="info">
</div>
</div>
<div id="hiddenDivs" style="display:none;">
<div class="info" id="option1">Box</div>
<div class="info" id="option2">Google Drive</div>
<div class="info" id="option3">Box</div>
</div>
</body>
<script>
$('.buttons button').click(function (){
$('#info').empty();
$('#info').html($("#" + $(this).data('link')).html());
});
</script>
Example : https://jsfiddle.net/yvsu6qfw/3/
It sounds like maybe you were looking for using the button itself to populate data built into the button with a data attribute or something? If so you can do something like this:
HTML
<div class="button-panel">
<ul id="button-column" style="list-style: none;">
<li class="buttons"><button data-info="Box">Button 1</button></li>
<li class="buttons"><button data-info="Google Drive">Button 2</button></li>
<li class="buttons"><button data-info="Box">Button 3</button></li>
</ul>
</div>
<div id="info-div">
<div id="info"></div>
</div>
jQuery
$(document).ready(function (){
$('#button-column button').click(function (){
$('#info').html($(this).attr('data-info'));
});
});
If you want the first button to load the content from the first hidden div etc. without relying upon using the id attributes, you can use the .index() method. When you pass this as an argument it will return the index value of the click event target in the collection $("#button-column .buttons :button"). Afterwards you can pass the index value to the .get() method to retrieve the corresponding element from the collection of hidden divs $("#hiddenDivs .info").
$().ready(function(){
$("#button-column .buttons :button").on("click", function(){
$('#info').empty();
var clickedIndex = $("#button-column .buttons :button").index(this);
var hiddenInfo = $("#hiddenDivs .info").get(clickedIndex);
$('#info').prepend( $(hiddenInfo).text() );
});
});
you can use html function, without parameter gets the content of the element
with parameter replaces the content with the string parameter
$(document).ready(function (){
$('#button1').click(function (){
$('#info').html( $('#option1').html() );
});
$('#button2').click(function (){
$('#info').html( $('#option2').html() );
});
$('#button3').click(function (){
$('#info').html( $('#option3').html() );
});
});
In your code example, you do for example:
$('#info').prepend('#option1');
What you instruct to do here, is adding a text string '#option1' to an element with ID info.
What you intend to do is prepending the content of ID option1 to the element with ID info. You could do something like this instead:
$('#info').prepend($('#option1').html());
Another approach could be (but I don't know if that's relevant for you) to not clone content (since it costs you repaints) but toggle the specific elements instead. For example:
$('#option1,#option2').hide();
$('#option3').hide();
And yet another one: use data-attributes on your buttons:
Button 1
Button 2
<div id="info">
</div>
And the JS:
$('.button').on('click', function(event) {
event.preventDefault();
$('#info').html($(event.currentTarget).attr('data-text'));
});
Don't repeat yourself! To get the number out of an ID replace with "" all that is not a number using RegExp \D.
Using number from ID
Than, to get the actual content you can use $("#option"+ num).html() or $("#option"+ num).text() methods:
jsFiddle demo
jQuery(function ($) {
$('.buttons button').click(function () {
var num = this.id.replace(/\D/g,"");
$("#info").html( $("#option"+ num).html() );
});
});
Target element using data-* attribute
Alternatively you can store inside a data-* attribute the desired target selector ID:
<button data-content="#option1" id="button1">Button 1</button>
and than simply:
jsFiddle demo
jQuery(function ($) {
$("[data-content]").click(function () {
$("#info").html( $(this.dataset.content).html() );
});
});
http://api.jquery.com/html/
http://api.jquery.com/text/
If the expectation is to get same indexed hidden div content, Then the below code should work.
$(document).ready(function (){
$('.buttons button').click(function (){
$('#info').empty();
var index = $('.buttons button').index($(this));
$('#info').html($('.info:eq('+index+')').html());
});
});
I'm using a tutorial to create an image gallery and it gives me an error on line 31 of the js file. Not familiar with jQuery language so I thought the code might be out of date. Tried using the migrate plugin and it still doesn't work. On the jQuery site it says .live() was removed and to use .on() instead but not sure how to do that.
html file:
<body>
<header>
<div class="container">
<nav id="navbar"></nav>
</div>
</header>
<section id="main">
<div class="container">
<ul id="gallery">
<li data-tags="Web Design, Logo Design, Print Design"><a class="fancybox" rel="group" href="img/1.jpg"><img src="img/1.jpg"></a></li>
<li data-tags="Logo Design"><a class="fancybox" rel="group" href="img/2.jpg"><img src="img/2.jpg"></a></li>
<li data-tags="Web Design"><a class="fancybox" rel="group" href="img/3.jpg"><img src="img/3.jpg"></a></li>
<li data-tags="Print Design"><a class="fancybox" rel="group" href="img/4.jpg"><img src="img/4.jpg"></a></li>
<li data-tags="Logo Design, Print Design"><a class="fancybox" rel="group" href="img/5.jpg"><img src="img/5.jpg"></a></li>
</ul>
</div>
<hr>
<footer>
<div class="container">
<p></p>
</div>
</footer>
</section>
<script src="js/jquery.js"></script>
<script src="js/jquery.quicksand.js"></script>
<script src="js/fancybox/jquery.fancybox.pack.js"></script>
<script src="js/fancybox/jquery.fancybox-buttons.js"></script>
<script src="js/fancybox/jquery.fancybox-media.js"></script>
<script src="js/fancybox/jquery.fancybox-thumbs.js"></script>
<script src="js/script.js"></script>
<script>
$(document).ready(function(){
$(".fancybox").fancybox();
});
</script>
</body>
javascript file:
$(document).ready(function(){
var items = $('gallery li'),
itemsByTags = {};
items.each(function(i){
var elem = $(this),
tags = elem.data('tags').split(',');
elem.attr('data-id',i);
$.each(tags,function(key,value){
value= $.trim(value);
if(!(value in itemsByTags)){
itemsByTags[value] = [];
}
//add image to array
itemsByTags[value].push(elem);
});
});
//create all items option
createList('All Items', items);
$.each(itemsByTags, function(k, v){
createList(k, v);
});
//click handler
$('#navbar a').live('click',function(e){
var link = $(this);
//add active class
link.addClass('active').siblings().removeClass('active');
$('#gallery').quicksand(link.data('list').find('li'));
e.preventDefault();
});
$('#navbar a:first').click();
//create the lists
function createList(text,items){
var ul = $('<ul>',{'class':'hidden'});
$.each(items, function(){
$(this).clone().appendTo(ul);
});
ul.appendTo('#gallery');
var a = $('<a>',{
html:text,
href:'#',
data:{list:ul}
}).appendTo('#navbar');
}
});
Adjusting live() to on() can be done as follows: currently you have a statement like this:
$('#navbar a').live('click',function(e){ ...
and, as you already found out, live() is deprecated as of jQuery version 1.7.
Adjusting this to on() means to let the static navbar delegate the click event to a tags that are children of the navbar, even if they are added later:
$('#navbar').on('click', 'a', function(e){..
The on() is bound to an element that is already in the DOM when the page is loaded and delegates events to child elements even if they are dynamically added later.
For reference: http://api.jquery.com/on/
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"} );