I don't really know how to explain this properly, but I'm learning how to use AJAX and while I've pretty much figured it out, I'm running into a problem with JQuery not referencing a call to a button that is regenerated at the end of a DIV. The reason this button is regenerated is because it's positioned inside of the div in which the content is being replaced. (In this case it's video cycling).
I've attatched a JSFiddle that shows my problem.
My javascript file is loaded at the bottom of my body, like so:
<html>
<head>
...
</head>
<body>
...
<script src="..."></script>
</body>
</html>
var i = 0;
$('#bar').on('click', function() {
i++;
$('#foo').html('<button id="bar">Test button: ' + i + '</button>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="foo">
<button id="bar">Test button: 0</button>
</div>
Because you are generating HTML dynamically with jQuery try Using event delegation :-
var i = 0;
$('#foo').on('click', '#bar' ,function() {
i++;
$('#foo').html('<button id="bar">Test button: ' + i + '</button>');
});
Or
var i = 0;
$(document.body).on('click', '#bar' ,function() {
i++;
$('#foo').html('<button id="bar">Test button: ' + i + '</button>');
});
Fiddle
Try this code
var i = 0;
$(document).on('click', '.bar' ,function() {
i = i+1;
$('#foo').html('<button class="bar">Test button: ' + i + '</button>'); // instead of .html() use .append() here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
<button id="bar" class="bar">Test button: 0</button>
</div>
Related
I am learning javascipt and now i have a piece of code but i am unable to get this to work, javascript isn't executed. I have already searched the web but i can't find an answer. Maybe you guys can help me with this.
HTML
<html>
<head>
<title>Text Game</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<button><span id="click">0</span></button>
</body>
</html>
Javascript
// Variables
var waarde = {
amount:2
};
$(document).ready(function() {
updateValues();
});
function updateValues() {
document.getElementById("click").innerHTML = waarde.amount;
}
$('#click').click(function() {
waarde.amount = waarde.amount + 1;
updateValues();
});
You have a couple of issues here:
Issue #1:
The element does not exist in the DOM to bind to yet, so do any or all of the following:
Move your script tag to the footer, right before the closing </body> tag (generally best practice anyway).
Use event delegation to bind to events on future elements.
Put all the JavaScript in the ready handler.
Issue #2:
You should not bind a click event handler on an element inside a button, it will not work in specification compliant browsers as the button consumes the event, and it not propagated to children.
See the HTML5 spec for button for reference:
Content model:
Phrasing content, but there must be no interactive content descendant.
Instead, bind the click event handler to the button itself.
// Variables
var waarde = {
amount: 2
};
$(document).ready(function(){
updateValues();
});
function updateValues(){
document.getElementById("click").innerHTML = waarde.amount;
}
// Binding to the button element using event delegation.
$(document).on('#button').click(function(){
waarde.amount = waarde.amount + 1;
updateValues();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button"><span id="click">0</span></button>
Also, unless you need the span element for something else, you could get rid of it and just use:
document.getElementById("button").innerHTML = waarde.amount;
You should put this code:
$('#click').click(function(){
waarde.amount = waarde.amount + 1;
updateValues();
});
Inside of $(document).ready(function(){}) function. $('#click') isn't in the DOM yet..
You have to write "Click" event in document.ready
var waarde = {
amount: 2
};
$(document).ready(function () {
$('#click').click(function () {
waarde.amount = waarde.amount + 1;
updateValues();
});
updateValues();
});
function updateValues() {
document.getElementById("click").innerHTML = waarde.amount;
}
The problem with your code is you are not assigning an event handler when javascript loads the js file. It should be called in the ready function.
var waarde = {
amount:2
};
$(document).ready(function(){
$('#click').click(function(){
waarde.amount = waarde.amount + 1;
updateValues();
});
});
function updateValues(){
document.getElementById("click").innerHTML = waarde.amount;
}
You should wrap it inside the ready method!
// Variables
var waarde = {
amount:2
};
$(document).ready(function() {
$('#click').click(function() {
waarde.amount = waarde.amount + 1;
updateValues();
});
});
function updateValues() {
document.getElementById("click").innerHTML = waarde.amount;
}
Here's a codepen link http://codepen.io/anon/pen/vKXQza
Two points:
You should put your jQuery event listener inside the document.ready.
There is no guarantee to work click event on span.
// Variables
var waarde = {
amount:2
};
$(document).ready(function(){
updateValues();
$('#click2').click(function(){
waarde.amount++;
updateValues();
});
});
function updateValues(){
document.getElementById("click2").innerHTML = waarde.amount;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<button id="click2">0</button>
You can see your problem solution is here
You are missing button click event in $(document).ready(function(){}(;
<html>
<head>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
function func(){
var s = "<p id=" + id +">"+"<center>"+"<h2><b>Topic :</b></h2>"+message+"</center></p><br>";
document.getElementById("stat").innerHTML+=s;
}
</script>
</head>
<body>
//call function func
<pre id="stat" > </pre>
</body>
</html>
Guys the function func is supposed to create a paragraph with id as "id " and the content as a message inside the tag with id as "stat " .. it works fine
But i cant use the 'Jquery' selector to use the click function on tag :/ !
the reason i am inserting inside in is i need the interpreter to consider "\n" as a new line.
Why is that , not working ?
and is there any other way to do it ?
Try this,
$(document).ready(function(){
$(document).on('click','p',function(){
$(this).hide();
});
});
$(document).on('click', 'p', function() { $(this).hide();})
The code you wrote is not working because the p element is not present when the document is loaded. Since the p element is dynamically added, you have to attach the event to the document object
the fastest way will be to change
var s = "<p id=" + id +">"+"<center>"+"<h2><b>Topic :</b></h2>"+message+"</center></p><br>";
to
var s = "<p id=" + id +" onclick=\"$(this).hide()\">"+"<center>"+"<h2><b>Topic :</b></h2>"+message+"</center></p><br>";
and delete this
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
This may help:
$('body').on('click', 'p', function(){
$(this).hide();
});
use .on() instead
$(document).on('click', 'p', function(){
$(this).hide();
});
.on() has to ability to add a click handler to elements that are created dynamically , like your <p> tags are
Attach the click event handler inside func:
function func(){
var s = "<p id=" + id +">"+"<center>"+"<h2><b>Topic :</b></h2>"+message+"</center></p><br>";
document.getElementById("stat").innerHTML+=s;
$("#" + id).click(function(){
$(this).hide();
});
}
Or better still:
function func(){
var s = $("<p id=" + id +">"+"<center>"+"<h2><b>Topic :</b></h2>"+message+"</center></p><br>");
$("#stat").append(s);
s.click(function(){
$(this).hide();
});
}
I have two buttons that are meant to activate my JavaScript functions when clicked, but they don't seem to work. However, when I move my JavaScript function content outside the functions, they work correctly. So the buttons are definitely the problem.
JavaScript:
$(document).ready(function()
{
function recordjourney()
{
var journey = JSON.parse(localStorage.getItem('journey'))||[];
journey.push(location.protocol + '//' + location.host + location.pathname);
localStorage.setItem('journey', JSON.stringify(journey));
document.write(journey);
}
function resetjourney()
{
localStorage.clear()
}
});
HTML:
<p><button name="record" type="button" onclick="recordjourney()">Record Journey</button</p>
<p><button name="reset" type="button" onclick="resetjourney()">Reset Journey</button></p>
The buttons aren't the problem, you have a scope issue since the functions you are calling don't exist on the same level as the buttons.
You can fix that and make your code a bit cleaner by binding to your buttons inside the ready call like so
$(document).ready(function() {
$('[name="record"]').click(recordjourney);
$('[name="reset"]').click(resetjourney);
});
function recordjourney() {
var journey = JSON.parse(localStorage.getItem('journey')) || [];
journey.push(location.protocol + '//' + location.host + location.pathname);
localStorage.setItem('journey', JSON.stringify(journey));
document.write(journey);
}
function resetjourney() {
localStorage.clear()
}
<p><button name="record" type="button">Record Journey</button</p>
<p><button name="reset" type="button">Reset Journey</button></p>
Fiddle here - http://jsfiddle.net/7eYNn/
initialize your functions out of $(document).ready().
$(document).ready(function()
{
});
function resetjourney()
{
localStorage.clear()
}
function recordjourney()
{
var journey = JSON.parse(localStorage.getItem('journey'))||[];
journey.push(location.protocol + '//' + location.host + location.pathname);
localStorage.setItem('journey', JSON.stringify(journey));
document.write(journey);
}
Yeah, that's right. If you define a function inside a function, it will be private to that function. You need to create a global var
var recordjourney;
$(document).ready(function(){
...
recordjourney = {
var journey =
... etc
Although, of course, given that you are using JQuery I'd do
$(document).ready(function(){
...
$( 'button[name=record]' ).bind( function(){
//put your function here
})
and remove the ugly onclick="recordjourney from the button tags.
I am trying to add a mouseup, mousedown, hover event on several different images - the only problem is that the event only occurs on the first image,
tried using the each() function does not seem to be working.
Any suggestions on how I can do this?
$(function() {
var filename = $('.imgover').attr('alt');
$('.rolloverimg').each(function(){
$('#'+ filename).mouseup(function(){
$(this).children("img").attr('src', 'content/images/buttons/'+ filename + '_up.png' );
}).mousedown(function(){
$(this).children("img").attr('src','content/images/buttons/' + filename + '_down.png');
});
$('#'+ filename).hover(
function () {
$(this).children("img").attr('src', 'content/images/buttons/'+ filename + '_hover.png');
},
function () {
$(this).children("img").attr('src', 'content/images/buttons/' + filename + '_up.png');
}
);
});
});
<div class="hdr-btns rolloverimg">
<img src="content/images/buttons/play_up.png" alt="play" id="play" class="imgover" />
<img src="content/images/buttons/register_up.png" alt="register" id="register" class="imgover" />
</div>
There is no need to implement a loop in order to add events to multiple elements using jQuery. You can simply apply the events to a selector that selects all the elements that you need.
For example, the following code adds MouseUp and MouseDown events to all the img tags inside an element that has the rolloverimg class:
$('.rolloverimg img').mouseup(function () {
alert('up')
}).mousedown(function () {
alert('down');
});
And if you want to quick test it, here is the full working example that was created starting from your source code:
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$(function () {
$('.rolloverimg img').mouseup(function () {
alert('up')
}).mousedown(function () {
alert('down');
});
});
</script>
</head>
<body>
<div class="hdr-btns rolloverimg">
<img src="content/images/buttons/play_up.png" alt="play" id="play" class="imgover" />
<img src="content/images/buttons/register_up.png" alt="register" id="register" class="imgover" />
<input type="button" value="text" />
</div>
</body>
</html>
Additional info update
If you do not want to select all the img tags from the div, but rather just the ones that have the imgover class applied to them, you can use the following selector:
$(function () {
$('.rolloverimg img.imgover').mouseup(function () {
alert('up')
}).mousedown(function () {
alert('down');
});
});
Additional info update2
You can access the currently selected element using $(this). For example:
$('.rolloverimg img.imgover').mouseup(function () {
alert($(this).attr('id') + '_up')
}).mousedown(function () {
alert($(this).attr('id') + '_down');
});
Please let me know if the above helps or if you need more specific help.
put the code:
var filename = $('.imgover').attr('alt');
inside the each function.
Here is a simple way to do it:
$('.rolloverimg').mouseover(function() {
$('img', this).each(function () {
$(this).attr('alt', $(this).attr('id') + '_over');
})
}).mouseout(function() {
$('img', this).each(function () {
$(this).attr('alt', $(this).attr('id') + '_out');
})
});
Of course, juste replace the attr('alt', 'in') to do what you need (set the src attribute), it is just a simple way to show the logic of selecting the elements.
You may just use $('.rolloverimg img').mouseup() etc.
$('.rolloverimg img').mouseup(function(){
$(this).children("img").attr('src', 'content/images/buttons/'+ filename + '_up.png' );
}).mousedown(function(){
$(this).children("img").attr('src','content/images/buttons/' + filename + '_down.png');
});
$('.rolloverimg img').hover(
function () {
$(this).children("img").attr('src', 'content/images/buttons/'+ filename + '_hover.png');
},
function () {
$(this).children("img").attr('src', 'content/images/buttons/' + filename + '_up.png');
}
);
Can someone tell me why the following is not working?
<head>
<script language="javascript" src="/assets/js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$("button").bind("click", function() {
alert("You clicked " + $(this).attr("id"));
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<button id="button1">Click Me!</button> <button id="button2">Click Me!</button> <button id="button3">Click Me!</button> <button id="button4">Click Me!</button> <button id="button5">Click Me!</button>
</body>
Nothing is happening when I click on any of the buttons.
Dave
Try:
$(document).ready(function() {
$("button").bind("click", function() {
alert("You clicked " + $(this).attr("id"));
});
});
Edit:
As stated by Alex Sexton, the use of live instead of bind is also preferable when you have to apply the same function to more than 2 elements of the same type.
Follow the link for more infos, credits to him.
You need to bind the click handler when the DOM is ready:
$(function() {
$("button").bind("click", function() {
alert("You clicked " + $(this).attr("id"));
});
});
Another solution would be to use event delegation, so it doesn't matter that the buttons don't exist yet.
$("button").live("click", function() {
alert("You clicked " + $(this).attr("id"));
});
Because your javasript code is executed before html body is loaded. You should call your JS after html is fully loaded. You can do it so:
$(function() { // it's called when document loads
$("button").bind("click", function() {
alert("You clicked " + $(this).attr("id"));
});
});
But it's good practice not to inject your code into global scope. You can do it so:
(function() { // it helps you not to inject your code into global scope
$(function() { // it's called when document loads
$("button").bind("click", function() {
alert("You clicked " + $(this).attr("id"));
});
});
})();