Custom Jquery Not Available At Runtime With Dynamicallly Added Html - javascript

I have a page that looks like this..
<!DOCTYPE html>
<html>
<head>
<title>JQM</title>
<meta charset=utf-8 />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.css">
<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script src="http://code.jquery.com/mobile/latest/jquery.mobile.js"></script>
<script>
$(function(){
$('[data-role="list-divider"]').toggle(function(){
$('.'+$(this).attr('data-link')).addClass('show');
$(this).children().removeClass('ui-icon-plus').addClass('ui-icon-minus');
},function(){
$('.'+$(this).attr('data-link')).removeClass('show');
$(this).children().removeClass('ui-icon-minus').addClass('ui-icon-plus');
});
});
</script>
</head>
<body>
<div data-role="page">
<div data-role="header">
</div>
<div data-role="content">
</div>
</div>
</body>
</html>
I am adding html in dymanically from the server in the content area. The problem is that when I add the content dynamically, the jquery function that I created statically on the page doesnt engage..
<script>
$(function(){
$('[data-role="list-divider"]').toggle(function(){
$('.'+$(this).attr('data-link')).addClass('show');
$(this).children().removeClass('ui-icon-plus').addClass('ui-icon-minus');
},function(){
$('.'+$(this).attr('data-link')).removeClass('show');
$(this).children().removeClass('ui-icon-minus').addClass('ui-icon-plus');
});
});
</script>
If I add the html statically all the code works fine and everything is good. My question is how do I make this jquery available to run once html is added to the page from the server?
I DID THIS AND IT WORKED, is there a more elegant way using .on or is this fine?
//got html blob
deferred.success(function (res) {
$(function () {
$('[data-role="list-divider"]').toggle(function () {
$('.' + $(this).attr('data-link')).addClass('show');
$(this).children().removeClass('ui-icon-plus').addClass('ui-icon-minus');
}, function () {
$('.' + $(this).attr('data-link')).removeClass('show');
$(this).children().removeClass('ui-icon-minus').addClass('ui-icon-plus');
});
});
});

Since the jquery is currently ran when the document is ready and your content is not loaded yet it won't find the elements and wire-up the events. Adding your script to the ajax.success should solve your problem.

looking at your code, I don't see where you're loading the content dynamically. But if you want that script to run. You should try a document.ready() in front of that script

You can't bind event handlers to elements that haven't been created. Check out this:
http://api.jquery.com/on/

Try this:
$(function(){
$(document).on('toggle', '[data-role="list-divider"]', function(){
$('.'+$(this).attr('data-link')).addClass('show');
$(this).children().removeClass('ui-icon-plus').addClass('ui-icon-minus');
},function(){
$('.'+$(this).attr('data-link')).removeClass('show');
$(this).children().removeClass('ui-icon-minus').addClass('ui-icon-plus');
});
});
Haven't tested it though. For on('click') this usually works.
What you do is you bind the 'toggle' trigger to the whole document ( $(document) ) and then check on what element is was triggered. This way you can detect elements that were created after the initialization of the DOM.

You have to use jquery .On() method to attach even handlers to contents dynamically added to pages. Check this - .on
Some thing lik this might work (didn't test) :-
$(function(){
$('[data-role="list-divider"]').on('toggle' ,function(event){
$('.'+$(this).attr('data-link')).addClass('show');
$(this).children().removeClass('ui-icon-plus').addClass('ui-icon-minus');
},function(event){
$('.'+$(this).attr('data-link')).removeClass('show');
$(this).children().removeClass('ui-icon-minus').addClass('ui-icon-plus');
});
});

Related

JavaScript - Loading the entire webpage not specific div

I'm new to JavaScript and I'm sure that this is a very trivial fix.
I'm dynamically changing a div content based on which button is clicked. This example works in JSFiddle but however when I put it on my PC it simply loads the entire webpage even when I wrap the JS with $(window).load(function(){ ... })
My HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src= "http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<ul class="menu">
<li>About</li>
<li>Contact</li>
<li>Misc</li>
</ul>
<div id="about" class="menu-content">About</div>
<div id="contact" class="menu-content">Contact</div>
<div id="misc" class="menu-content">Misc</div>
</body>
</html>
My JS (script.js):
$(window).load(function(){
var $content = $('.menu-content');
function showContent(type) {
$('div', $content).hide();
$('div[data-menu-content='+type+']').show();
}
$('.menu').on('click', '.menu-btn', function(e) {
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
});
showContent('about');
});
$(window).load(function(){ ... })
replace by :
$(document).ready(function(){ ... })
Replace your (window).load to (document).ready
load is called when all assets are done loading, including images. ready is fired when the DOM is ready for interaction.
load()
The load event fires at the end of the
document loading process. At this
point, all of the objects in the
document are in the DOM, and all the
images and sub-frames have finished
loading.
ready()
While JavaScript provides the load
event for executing code when a page
is rendered, this event does not get
triggered until all assets such as
images have been completely received.
In most cases, the script can be run
as soon as the DOM hierarchy has been
fully constructed. The handler passed
to .ready() is guaranteed to be
executed after the DOM is ready, so
this is usually the best place to
attach all other event handlers and
run other jQuery code. When using
scripts that rely on the value of CSS
style properties, it's important to
reference external stylesheets or
embed style elements before
referencing the scripts.
try this
$(document).ready(function(){
var $content = $('.menu-content');
function showContent(type) {
$('div', $content).hide();
$('div[data-menu-content='+type+']').show();
}
$('.menu').on('click', '.menu-btn', function(e) {
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
});
showContent('about');
});
You can try below solution :
function showContent(type) {
$($content).hide();
$('#'+type).show();
}
When i ran your snippet in my PC, I found out that Jquery was not able to find div, based on the selectors you have specified at the time of loading.

JQuery function .load not working

I have the next code. What am trying to do is when i refresh or open the page, to add the class intro. But my main problem is in the part :
$("body").load(function(){
I want when the page is opened, then to add the class .intro. Instead of body, i have also tried html, and still doesn't work.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("body").load(function(){
$("p").addClass("intro");
});
});
</script>
<style>
.intro {
background-color:green;
}
</style>
</head>
<body>
<img src="https://k32.kn3.net/taringa/1/9/3/9/4/7/32/johnny_te_toco/330x330_248.gif" width="304" height="236">
<p><b>Note:</b> Depending on the browser, the load event may not trigger if the image is cached.</p>
</body>
</html>
You should not use load() for this purpose.
load() function description : Load data from the server and place the returned HTML into the matched element.
You need just ready function to achieve that :
$(document).ready(function(){
$("p").addClass("intro");
});
//OR
jQuery(function($){
$("p").addClass("intro");
});
Hope this helps.
Try this instead:
$(document).ready(function(){
$(window).load(function(){
$("p").addClass("intro");
});
});
Load event attached to the window. If that is what you meant? Load on a DOM element like that doesn't make much sense.
Whilst this should work, you could pull it out of your ready() event.
$(document).ready(function(){
// Nothing to see here...
});
$(window).load(function(){
$("p").addClass("intro");
});
This waits for the load of the window, but if you just want to add the class as soon as possible when the DOM is ready, well, you won't need the load() at all:
$(document).ready(function(){
$("p").addClass("intro");
});
Bonus: You should use on() to attach all events going forward.
$(window).on('load', function(){
$("p").addClass("intro");
});
on() is the preferred method for events in future jQuery versions, as older methods are deprecated.
All the best.
Put your code inside $(document).ready callback.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").addClass("intro");
});
</script>
<style>
.intro {
background-color:green;
}
</style>
</head>
<body>
<img src="https://k32.kn3.net/taringa/1/9/3/9/4/7/32/johnny_te_toco/330x330_248.gif" width="304" height="236">
<p><b>Note:</b> Depending on the browser, the load event may not trigger if the image is cached.</p>
</body>
</html>
$(window).on('load', function(){
$("p").addClass("intro");
});

jQuery simple button bind

I'm new to jQuery, so this should be a simple question.
As far as I understand, I can bind a method to listen to an event, such as the click of a button, using
$('#buttonID').bind('click', function (){//some code});
However, this isn't working for me, so I must be doing something wrong.
This is my simple html file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js'></script>
<script src='test.js'></script>
</head>
<body>
<input id="SignIn" type="button" value="Sign In"></input>
</body>
</html>
Apart from loading jQuery files, it loads file test.js, which looks like this:
// JavaScript Document
$('#SignIn').bind('click', function() {alert('hi');});
Is that not enough for binding? I was hoping this would fire an alert dialog, but it doesn't, it seems the callback is not executed at all.
What is wrong here? Both files (html and js) are located in the same directory, and Google Chrome does not complain about anything in the JavaScript console, so from that end, everything should be fine.
Thanks for all help!
Wrap your code in document ready handler. It accepts a function which executes when DOM is fully loaded.
As you are using jQuery 1.3
$(document).ready(function() {
$('#SignIn').bind('click', function() {
alert('hi');
});
});
For jQuery 1.7+,
$(document).ready(function() {
$('#SignIn').on('click', function() {
alert('hi');
});
});
Additionally, As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.
$(function(){
$('#SignIn').bind('click', function() {alert('hi');});
})
Try
$(function(){
$('#SignIn').click(function() {alert('hi');});
});
Move your Javascript to the bottom of the HTML page, right above the closing body tag.
That way the DOM is ready when it is loaded, and there's no need for $(document).ready() calls.
https://developer.yahoo.com/performance/rules.html#js_bottom
You may want to include your JavaScript files at the very bottom, and everything should work as expected. It is recommended to do this and to include CSS files at the top (head tag). For more information see link included by #Grim...
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<input id="SignIn" type="button" value="Sign In"></input>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js'></script>
<script src='test.js'></script>
</body>
</html>
$( "#target" ).click(function() {
//Write some code here
});
You can try this.
$(document).ready(function(){
$('#SignIn').on('click', function() {alert('hi');});
});
You can use this.
$(document).ready(function () {
$("#SignIn").click(function () {
alert('demo');
});
});

jQuery preventDefault() issue

My problem is that there is no way to make preventDefault() work.
Here is my code:
HTML:
<a class="list-ui-controlcol-link list-ui-controlcol-link-delete" href="http://localhost/lmvc_trunk/pages/delete/17">Törlés</a>
JQUERY:
$(".list-ui-controlcol-link-delete").click(function(event){
event.preventDefault();
});
Even if I copy-paste the original example from jQuery's own site (http://api.jquery.com/event.preventdefault/) it is not working.
Could you explain me why this happening and how to make preventDefault work correctly?
You need to make sure that your script is executed after the DOM is loaded:
$(document).ready(function() {
$(".list-ui-controlcol-link-delete").click(function(event){
event.preventDefault();
});
});
See this page for more details: http://api.jquery.com/ready/
Where do you include your script? If you include the script in HEAD when the script loads there's no a.list-ui-controlcol-link-delete is present in the DOM.
Try doing this:
<html>
<head>
<title>test</title>
</head>
<body>
Torles
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="app.js"></script>
</body>
</html>
Where app.js contains:
$('.list-ui-controlcol-link-delete').click(function(e) { e.preventDefault(); });
Although I'd recommend using the .on() function as it will dinamically bind the events on newly generated DOM elements:
$(document).on('click','.list-ui-controlcol-link-delete',function(e) { e.preventDefault(); });

event.preventDefault not working as it should

I loaded data using AJAX in a div.
<div id="container">
<a class="hello" href="abc.php">hello</a> // loaded using ajax
<div>
Now I have jQuery:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('.hello').on("click",function(e){
e.preventDefault();
});
});
</script>
However it's not working as it should, i.e. it's directing me to abc.php. Where am I going wrong ?
Use .on as your a tag is loaded dynamically
$('#container').on("click",".hello",function(e){
e.preventDefault();
});
The .on() should be set up like this to work with dynamically created elements. Also, make sure to use Jquery version 1.8 or earlier versions.
Try:
$('#container').on("click",'.hello',function(e){
e.preventDefault();
});
It also work from this..
$('.hello').click(function(){
e.preventDefault();
});

Categories

Resources