I have two very similar function that are called on different events i.e. 1st on 'onmousedown' and 2nd on 'onmouseup' . I am thinking to merge them into one to improve maintainability of my code. My problem is how could I find the current event inside switch statement ?
function update_button_to_idle(id){
var img = 'images/';
switch(id){
case 'abc1':
img += 'enter1.png';
break;
case 'abc2':
case 'abc3':
img += 'play1.png';
break;
}
$('#' + id + ' img').attr('src', img);
}
function update_button_to_active(id){
var img = 'images/';
switch(id){
case 'abc1':
img += 'enter2.png';
break;
case 'abc2':
case 'abc3':
img += 'play2.png';
break;
}
$('#' + id + ' img').attr('src', img);
}
Instead of using onXXX attributes, bind your handlers using jQuery:
$("selector").on("mousedown mouseup", function(event) {
update_button(this.id, event.type);
}
Then combine your functions into one update_button() function that takes two arguments.
Depending on how the event is registered - if you pass in the event to the function you can identify it by calling the event.type. For example:
function (event) {
if (event.type == "mousedown") {
}
}
Without knowing more about how the event is triggered, its hard to give you a complete answer.
Related
I have a bit of a problem, i have just inherited a colleague script and while i maintain his code, i am rewriting his, so that being said my problem is with the check boxes i can change the checks but after that i want to send the box that has been changed the element
so here is the on when i do the change
$(":checkbox[value=" + valu + "]").prop("checked","true");
and then i want to send it to his function: add2this(this, type);
var arrTmp // global array
function test( valu ){
$(":checkbox[value=" + valu + "]").prop("checked","true");
add2this(this, 'List');
}
function add2this(ths, type){
switch (type) {
case "List":
if (ths.checked) {
arrTmp.push(vl);
}
break;
default:
break;
}
}
hopefully the code will help to understand better
thanks
Your function is not passing the checkbox itself. You are using keyword "this" in a place where it does not mean what you think it means. You need to use jquery .each() .
function test( valu ){
$(":checkbox[value=" + valu + "]")
.prop("checked","true")
.each(function(){ add2this(this, 'List'); });
}
I want to create DOM elements with info taken from input type text. To be more specific:
I want the user to be able to write a location and after he presses "Go!" button an element to be created with the text inserted and I also want to have a delete icon which when pressed to delete that insert.
I created a function in which I took the input value but I cannot create the 'del' button
If I create another <img> inside using the same method, when I create the second entry it will put another <img> to the previous entry
search_btn.click(function() {
var place_reg = /^[a-z]+\d*[a-z]*(\s[a-z]+\d*[a-z]*)*?$/i;
var search_value = search_box.val();
var final_result = search_value.trim();
if (place_reg.test(final_result)) {
createDest(final_result);
} else {
alert('Please insert a valid destination');
}
document.getElementById('search_box').value = "";
});
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){ return txt.charAt(0).toUpperCase() +
txt.substr(1).toLowerCase();});
}
function createDest(value) {
var destination_i_search = document.createElement("div");
destination_i_search.innerHTML = toTitleCase(value);
destination_i_search.setAttribute("class" , "place");
$("#dest").append(destination_i_search);
}
It is very difficult to understand what you wish it to do, without a full example, but from comments you may want something like this:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/s6hn0n18/6/
I have converted it to use jQuery where appropriate.
var search_btn = $('#search');
var search_box = $('#searchbox');
search_btn.click(function () {
var place_reg = /^[a-z]+\d*[a-z]*(\s[a-z]+\d*[a-z]*)*?$/i;
var search_value = search_box.val() || "";
var final_result = search_value.trim();
if (place_reg.test(final_result)) {
createDest(final_result);
} else {
alert('Please insert a valid destination');
}
search_box.val("");
});
function toTitleCase(str) {
return str.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
function createDest(value) {
// use a div container
var div = $("<div/>");
div.html(toTitleCase(value));
div.addClass("place");
// If you want to replace the previous entry
$("#dest").append(div);
var del = $('<input class="delete" type="button" value="X"/>');
$("#dest").append(del);
}
// This is a delegated event handler, attached to a non-changing ancestor
$(document).on('click', '.delete', function(){
// Remove the previous div (if of class place)
$(this).prev('.place').remove();
// Remove the delete button too
$(this).remove();
});
The key is to add a delegated event handler for the delete buttons. These work by listening for the specified event (click in this case) bubbling up to a non-changing ancestor. It the applies the jQuery selector. It the calls the function for any matching element that caused the event. The default ancestor is document if nothing closer to the changing content is available. In this case you could use #dest
e.g.
$('#dest').on('click', '.delete', function(){
I feel silly asking this question. I have a javascript problem that I have been trying to solve since spring break.
I dynamically create divs to contain ratings for a product. But when I click on one of them, it always returns the last one.
for(var i=0; i < 5; i++) {
// Create Class called divReview
var divReview = document.createElement("div");
divReview.className = "divReview";
counter_ratings++;
var s = counter_ratings.toString();
divReview.id = "ratings" + s;
divReview.innerHTML = divReview.id;
$( divReview ).click(function() {
alert("You clicked " + divReview.innerHTML);
});
mainContainer.appendChild(divReview);
}
Here's the fiddle:
http://jsfiddle.net/alvasay/a9GZq/4/
I am pretty sure this is a simple problem, but I just can't see where I'm doing wrong. Thanks!
As mglison said, late binding. Alternative solution though is to use this in place of divReview in your click handler to reference the element being clicked.
$( divReview ).click(function() {
alert("You clicked " + this.innerHTML);
});
http://jsfiddle.net/a9HAH/
You're experiencing late binding. At the time the function is called, the value of divReview is the last value it had in the loop. I've solved it by creating a function which wraps the actual function to return so that you get the correct value from the closure:
Essentially, the code is something like:
for (...) {
...
var funcMaker = function(divRev) {
return function() {
alert("you clicked " + divRev.innerHTML);
};
};
$( divReview ).click(funcMaker(divReview));
}
http://jsfiddle.net/a9GZq/9/
Apart from the problem mentioned by mgilson, you have an odd mix of plain JS and jQuery. Here's a shorter version
for (var i = 1; i < 6; i++) {
var divReview = $('<div id="ratings' + i + '" class="divReview">ratings' + i + '</div>');
$('#gameContainer').append(divReview);
divReview.click(function() {
alert("You clicked " + this.innerHTML);
});
}
I am trying to add multiple event listeners to elements that are being dynamically added to a page. I have attempted to use the on() function, as instructed in many posts but none of them seem to work for. When the page is clicked, a new should be added, with formatting determined by the correct CSS class. When a particular is focused, it should be movable using WASD and the jquery animate(). Here is what I have right now:
$(document).ready( function() {
var $index = 0;
$('div').on('keydown', 'div' , function(key) {
switch(parseInt(key.which,10)) {
case 87: //W
$(this).animate({top: '-=10px'}, 'fast');
break;
case 65: //A
$(this).animate({left: '-=10px'}, 'fast');
break;
case 83: //S
$(this).animate({top: '+=10px'}, 'fast');
break;
case 68: //D
$(this).animate({left: '+=10px'}, 'fast');
break;
default:
break;
}
});
$(document).click( function() {
// if(key.which == 13)
{
var $toadd = "<div class='";
switch($index % 4)
{
case 0:
$toadd += "red' tabindex='"+ ($index + 1) + "'></div>";
$index++;
break;
case 1:
$toadd += "green' tabindex='"+ ($index + 1) + "'></div>";
$index++;
break;
case 2:
$toadd += "blue' tabindex='"+ ($index + 1) + "'></div>";
$index++;
break;
case 3:
$toadd += "yellow' tabindex='"+ ($index + 1) + "'></div>";
$index++;
break;
default:
break;
}
$('body').append($toadd);
// $('body').on('click keydown','div', function() {
// $('body').append($toadd);
// });
}
});
});
Currently, the DIVs are added by clicking the page, but cant be moved using WASD. The s are focusable for the animate function to work. If I remove the dynamically adding by clicking and place a few static s, it works great.
Thanks for anything you can offer!
You need to use on() for event delegation in your case.
$(document).on('keydown', '.red, .green, .blue, .yellow' , function(key) //Instead of document use a container that exists in DOM at any given time to have the event delegated to these divs.
With this you attach the event to document head or any container that holds these divs and which inturn will be delegated to any of these divs present now or added for the future.
i have the following function to swap images on the click of a ul in a nested list, but it doesnt stop bubbling up the list..
function bimageswap (step) {
step.stopPropagation;
realstep = parseInt(step) + 1;
nextsteps = realstep + 1;
for (iss = nextsteps;iss <= 5; iss++) {
document.getElementById("step" + iss).className = 'step' + iss;
alert(iss);
}
document.getElementById("step" + realstep).className = 'step' + realstep + 'a';
/*$("#step2").css( 'background-image', 'images/adtl_prodimg/discs/step1_.png');*/
return false;
}
it is called like this:
<ul onclick='return bimageswap("4")'>
i tried the return because it is what i found in another answer but it still doesnt work. i would greatly appreciate any help thanks!
The stopPropagation method is in the event object, you can't call it on a string. You are also missing the parentheses, so it would just get the stopPropagation property from the string (which returns undefined) and discard it.
Send the event object from the event handler to the function:
<ul onclick="bimageswap(event, '4');">
Use the event object in the function:
function bimageswap(event, step) {
event.stopPropagation();
...