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;
...
}
);
Related
understand me
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script>
$('.deleteMe').live('click', function(){
$(this).parent().remove();
$('#contributionList').listview('refresh');
});
$( document ).ready(function() {
$('#addContribution').click(function () {
var newAmount = $('#contributionAmount').val();
if (newAmount) {
$('#contributionList').append('<li><a>' + newAmount + '</a><a class="deleteMe"></a></li>').listview('refresh');
$('#contributionAmount').val('');
} else {
alert('Nothing to add');
}
});
});
</script>
</head>
<body>
<div data-role="page" id="home">
<div data-role="content">
<ul data-role="listview" id="contributionList" data-split-icon="delete" data-split-theme="d">
<li id="l1"><a>5.00</a><a id="1" class="deleteMe"></a></li>
<li><a>10.00</a><a class="deleteMe"></a></li>
<li><a>15.00</a><a class="deleteMe"></a></li>
<li><a>20.00</a><a class="deleteMe"></a></li>
<li><a>25.00</a><a class="deleteMe"></a></li>
<li><a>50.00</a><a class="deleteMe"></a></li>
<li><a>100.00</a><a class="deleteMe"></a></li>
</ul>
<br />
<fieldset class="ui-grid-a">
<div class="ui-block-a">
<input type="text" placeholder="Add new Amount" id="contributionAmount" />
</div>
<div class="ui-block-b">
<input type="button" value="Add" id="addContribution"/>
</div>
</fieldset>
</div>
</div>
</body>
</html>
^ this code is work in website but when i add it to HTML like this is never work .. i don't know why !
look at the last answer in down someone sent me a link is work !
but when i add it in HTML not work
------- >< >< ><
some people say u don't use $(document).ready(function() {});
and some people say you can use $('ID').on('click',function(){})
^ i did that in my computer it ain't work ! but i didn't test it in website
<><><----------
the problem maybe in my laptop Mac Os X if the code is work then it
should work when i add it in HTML is not work
basically code work in website but in HTML inside not work !
<script>
$( document ).ready(function() {
$('#addContribution').click(function () {
var newAmount = $('#contributionAmount').val();
if (newAmount) {
$('#contributionList')
.append('<li><a>' + newAmount + '</a><a class="deleteMe"></a></li>')
.listview('refresh');
$('#contributionAmount').val('');
} else {
alert('Nothing to add');
});
});
</script>
The script didn't work because the dom element that you are binding ie;'#contributionAmount' is not available when the script is parsed by browser. document.ready event would be compiled by browser once the html dom is ready.
You have to register your click event inside document.ready event. document.ready event call after DOM is loaded. So when your older script executed DOM is not ready so you can't register your event.
If you don't want to do this jQuery ready event, you can bind a function to an event using on, Event Handler Attachment jQuery .on()
<script>
$('#addContribution').on('click',function() {
var newAmount = $('#contributionAmount').val();
</script>
This code will help as it works fine
$( document ).ready(function() {
$('#addContribution').click(function () {
var newAmount = $('#contributionAmount').val();
if (newAmount) {
$('#contributionList').append('<li><a>' + newAmount + '</a><a class="deleteMe"></a></li>').listview('refresh');
$('#contributionAmount').val('');
} else {
alert('Nothing to add');
}
});
});
check out this fiddle http://jsfiddle.net/uiupdates/NXrRp/492/
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
With the following piece of code:
<html>
<head>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$j = JQuery.noConflict();
function test() {
$j("#li1").on(
"click",
function() {$j.ajax({
url : "user/create_user_view",
success : function(result) {
$j("#div1").html(result);
}
});
});
}//test()
$j(function(){
test();
});
</script>
</head>
<body>
<ul>
<li id="li1">li1</li>
<li id="li2">li2</li>
</ul>
<div id="div1">div1</div>
<div id="div2">div2</div>
</body>
</html>
Actually the result of ajax call is a html file which is indeed a form,
I want to register events to the added elements of .html file,
I know about $("parent-selector").on("event","child-selector",callback(){
// code here
});
How to register js events to elements added dynamically through ajax in div1?
Update:
My question is using $("parent-selector").on("event","child-selector",callback(){
// code here
});
will register events only to direct children of #div1 or its descendents too?
You can easyli attach eventhandlers to dynamic elements, you have to write it a little bit diffrent:
$('body').on('click', '.myDynamicElement', function(ev) {
// Do your stuff in here...
});
Take a look into this Demo, Cheers Jan
I'm playing around with event-delegation from http://learn.jquery.com/events/event-delegation/
.I have the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="A small web app to manage todos">
<title>TO-DO jQuery Tests</title>
<!--src attribute in the <script> element must point to a copy of jQuery -->
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$( "article" ).on( "click","a", function() {
console.log( "The ID attribute of the link is: " + $(this).attr('id'));
});
//The .append()method inserts the specified content as the last child of each element in the jQuery collection -->
$( "#test-container" ).append("<article> <a href=\"#\"id='link-2'>Link 2</a> </article>" );
});
</script>
</head>
<body>
<div id="test-container">
<article>
Link 1
</article>
</div>
</body>
When I click on Link2 I get no output on the console? Why isn't the event-handling working?
You have to bind to the closest static parent.
This case test-container.
$( "#test-container" ).on( "click","article a", function() {
// your code
});
The problem is that the second link is added dynamically and the click binding happens before the second link exists. That's why it has no affect on it.
Your code should look like this (instead of $(document) you can also use any static parent container as Ricardo pointed out):
$(document).ready(function() {
$(document ).on( "click","article a", function() {
console.log( "The ID attribute of the link is: " + $(this).attr('id'));
});
//The .append()method inserts the specified content as the last child of each element in the jQuery collection -->
$( "#test-container" ).append("<article> <a href=\"#\"id='link-2'>Link 2</a> </article>" );
});
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.