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.
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(){}(;
So I have multiple delete buttons on a table and each button has there own unique id. I am trying to get this value via javascript but I can't get it to work at all.
Here is a section js that is working properly and loads the correct html (this is ran for each movie):
function createRow(movie) {
movie.NewDate = new Date(movie.ReleaseDate);
return '<tr><td><img class="movieImage" src="' +
movie.ImageLink +
'" alt="' +
movie.Title +
' Image" style="width:50px;height:75px">' +
'<td>' +
movie.Title +
'</td><td>' +
movie.NewDate.toLocaleDateString("en-US") +
'</td><td><button type="button" class="removeButton" value="' + movie.DVDID + '">Delete</button></td></tr>';
}
And here is the js where I am trying to retrieve the id:
$(document)
.ready(function () {
var deleteButtons = $(".removeButton");
deleteButtons.each(function (index) {
var currentButton = $(this);
var buttonValue = currentButton.val();
currentButton.click(function () {
alert(buttonValue);
});
});
});
I found the last snippet via Click one of multiple buttons, put value in text input
Right now just getting a proper alert would be sufficient.
Have you tried this approach:
$("#tableId").on("click", ".removeButton", function(){ alert($(this).attr("value")); })
This "on" binds all the ".removeButton" elements with the given function when click is triggered.
Your javascript should look like this:
$(document).ready(function () {
var deleteButtons = $(".removeButton");
deleteButtons.on('click', function() {
alert($(this).attr('value'));
});
});
Also, since you adding these buttons dynamicly with javascript, you may need to rebind button click events after you add new row. Also binding should be done after loading button html to DOM.
Since you are creating buttons dynamically, you won't be able to reach them properly because when the javascript was initiated they didn't exist in the DOM. So in order for you to be able to find the buttons, you'll have to look at the document scope and then find which button (class) you click on, like so:
$(document).on('click', '.removeButton', function(){
console.log($(this).val())
})
See fiddle for complete example
I want to make automate color parent changer in my js.
here is my html :
<div id="parent">
<div id="target" >
traget
</div>
</div>
And here is my js :
function ColorBox(target_id, btn) {
this.parent = $("#" + target_id).parent();
this.color = $(this.parent).append('<div class="color" >ops</div>');
$(this.color).append('<button class="change" value="' + btn + '">' + btn + '</button>');
this.ChangeColor = function (elm_id) {
$(this.parent).css('background', $(elm_id).val());
return true;
}
// here my problem start
$("#" + $(this.parent).attr('id') + " .change").bind('click', function () {
// how I can do it in here.
ColorBox.ChangeColor($(this));
});
}
$(document).ready(function () {
ColorBox('target', 'red');
});
I add some element to target parent and I want when clicked on change class the ColorBox.ChangeColor execute and but in bind method I can't use this.ChangeColor.
Now how I can do it ?
Try keeping the function's scope separate by assigning this to a variable (e.g. self). This will avoid any issues with accessing function variables and functions inside different scopes.
Here's a working demo: http://jsfiddle.net/37zq5/10/
Here you can see the code changes I made:
function ColorBox(target_id, btn) {
var self = this;
self.parent = $("#" + target_id).parent();
self.color = self.parent.append('<div class="color" >ops</div>');
self.color.append('<button class="change" value="' + btn + '">' + btn + '</button>');
$("#" + self.parent[0].id + " .change").on('click', function () {
self.parent.css('background', this.value);
});
};
$(document).ready(function () {
new ColorBox('target', 'red');
new ColorBox('target2','lime');
});
Personally I would probably do it this way. It's a bit of a different approach; you don't need this, you don't need new, and it's less code:
function ColorBox(target_id, btn) {
var $parent = $("#" + target_id).parent();
var $color = $('<div class="color">ops</div>').appendTo($parent);
var $button = $('<button class="change" value="' + btn + '">' +
btn + '</button>').appendTo($color);
$button.on( 'click', function (event) {
$parent.css('background', $button.val());
});
}
$(document).ready(function () {
ColorBox('target', 'red');
});
Whether you take this approach or do something more like #Joe's answer, there is one thing you should definitely change to work like I have it in this code. Your parent and color variables are both already jQuery objects; there is no need to wrap them in additional $() calls when you use them. So change the names of these variables to include the $ prefix as a reminder that they are jQuery objects, and then just use them directly where you need them instead of the extra $() wrapper.
If you use self as in #Joe's answer, then it would be code like:
self.$parent = $("#" + target_id).parent();
self.$color = self.$parent.append(...);
The $ prefix on these names isn't necessary, but it's a common convention to indicate a variable or property that is a jQuery object. It helps keep straight whether you need to use another $() around it.
Also, be aware that your parent and color variables are the same element. It looks like you're expecting color to be the <color> element, but it isn't. I changed the code so it is the <color> element.
I have the problem, that my javascript function isn´t when I press the button:
<script type="text/javascript" language="javascript">
(function ($) {
$.fn.addToList = function (opts) {
var input = $(this);
opts.button.click(function () {
opts.list.append("<li>" + input.val() + "</li>");
});
};
}(window.jQuery));
$("#zutat").addToList({
button: $("#btn"),
list: $("#list")
});
</script>
and
<input type="text" id="zutat" name="zutat"></input>
<input type="button" id="btn" value="Click">
<ul id="list"></ul>
How do I call this javascript function? What is my problem?
If your script tag is before the #zutat" stuff, then you are trying to manipulate on #zutat when the DOM elements are not ready yet. In this case, When the jQuery selector is being executed, it will not match the elements, since they are not available yet.
To fix it, you should wrap your codes by the $(document).ready function or put it at the bottom of body tag.
<script type="text/javascript" language="javascript">
(function($) {
$.fn.addToList = function(opts) {
var input = $(this);
opts.button.click(function() {
opts.list.append("<li>" + input.val() + "</li>");
});
};
$(document).ready(function() { // <<<<<<< execute after document ready.
$("#zutat").addToList({
button: $("#btn"),
list: $("#list")
});
});
})(window.jQuery);
</script>
I think you should move the parenthesis this way
})(window.jQuery);
In Firefox (I am using Firebug to test this) if you do this
function(){ alert("GONG"); }();
It gives you an error but if you wrap the function with parenthesis
(function(){ alert("GONG"); })();
The anonymous function will be executed.
You should also wrap the call to the dom elements in a $(document).ready(); call as showed in qiao's answer.
if you want to add <li>s to a <ul> when you click a button, you are going about it in a very round about way. you don't need to extend jquery or object prototype to do that.
try the following
$("#button").click(function() {
var val = $("zutat").val();
$("#list").append($("<li>" + val + "</li>"));
});
Normally the click event is handled like this
$('#btn').on("click",function(){
// code
});
I don't know what your code does exactly but not that what you want.
Trying to get a div that looks like <a id="thumblink-10"> to show and hide another div on hover, but no luck.
jQuery(document).ready(function() {
jQuery(document).find("a[id^='thumblink-']").live('hover', function(){
var num = this.id.split('-')[1];
jQuery('#thumb-hover-' + num).show();
}, function(){
//var num = this.id.split('-')[1];
jQuery('#thumb-hover-' + this.num).hide();
});
});
Thanks
This should work for you:
jQuery("a[id^='thumblink-']").live('hover', function(){
var num = this.id.split('-')[1];
jQuery('#thumb-hover-' + num).toggle();
});
Fixed the initial selector to not use find, only need to supply and single function for the hover and use the toggle function to show/hide the content.
http://jsfiddle.net/Zy2Ny/
But the way I would actually do it is to add data attributes to your links (can then change the selector to a class one instead) and use those to find the correct div to toggle like this:
JS
jQuery("a.thumblink").live('hover', function(){
var num = $(this).data('contentid');
jQuery('#thumb-hover-' + num).toggle();
});
HTML
<a class="thumblink" data-contentid="10">Hover</a>
<div id="thumb-hover-10" style="display: none;">Content</div>
http://jsfiddle.net/Zy2Ny/1/
You can't really do traversal methods like find and then use live. You should just use a standard selection. Also, you can't use live with hover and give two functions.
$("a[id^='thumblink-']").live('hover', function(){ // simple selector
Better still would be to use delegate and a map of events and handlers:
$(document).delegate('a[id^="thumblink-"]', {
mouseenter: function() {
},
mouseleave: function() {
}
});
I haven't been able to test it unfortunately, but I believe the following should work:
var id = 10;
$('#thumblink-' + id).hover(function(id) {
return function () {
$('#thumb-hover-' + id).show();
};
}(id),
function(id) {
return function () {
$('#thumb-hover-' + id).hide();
};
}(id)
);