Change image src back and forth after first click - javascript

What I want to happen is... when the image 'x' is clicked i want it to change image then when it is clicked again i want it to change back so on and so fourth, however I only want this to happen on the second click.
So X is clicked & nothing happens,
Then when it is clicked again it changes images,
and then back after another click, and then it alternates back and forth after that,
until the page resets, then i want it to reset as well.
this is my code so far:
document.getElementById('x').onclick = function() {
var ClickedOnce = 0;
if (this.src == 'Media/Images/Other/SwitchUP.jpg') {
ClickedOnce + 1
}
if (this.src == 'Media/Images/Other/SwitchUP.jpg' && ClickedOnce > 1) {
this.src = 'Media/Images/Other/SwitchDOWN.jpg';
} else if ('Media/Images/Other/SwitchDOWN.jpg') {
this.src = 'Media/Images/Other/SwitchUP.jpg';
}
}

It looks like the reason this isn't working is because you are declaring the var ClickedOnce inside of a function. This means that it is a local variable inside that function that will be set to 0 every time that function is called. Therefore, the same thing will happen every time it is clicked.
Try declaring some variable outside of the function.
You can try something like this:
var wasClicked = false;
document.getElementById('x').onclick = function() {
if (!wasClicked) {
wasClicked = true;
return;
}
if (this.getAttribute("src") == 'Media/Images/Other/SwitchUP.jpg') {
this.setAttribute("src", 'Media/Images/Other/SwitchDOWN.jpg');
} else {
this.setAttribute("src", 'Media/Images/Other/SwitchUP.jpg');
}
}
Additionally, since you tagged this question with jQuery, here is a jQuery approach to it:
var wasClicked = false;
$(document).ready(function() {
$("#x").click(function() {
if (!wasClicked) {
wasClicked = true;
return;
}
if ($(this).attr("src") == "path/to/some/image") {
$(this).attr("src", "path/to/other/image");
} else {
$(this).attr("src", "path/to/some/image");
}
});
});

Related

Cancelling function when clicked elsewhere than target div

I'm implementing inventory mechanics on my webgame and I want to complicate stuff a little.
In order to open the gate you need to find boltcutters. When you find it, you need to click on boltcutters and then on a chain to break it, and that's the part I have working.
But I want to implement some kind of function that if after clicking boltcutters I click anywhere but on the chain I want to run a function cancelling chain function (changing color) and displaying "Cant use it here" msg for example.
So in short, I need to find a solution where (pseudocode):
If(boltcutters_clicked){
if(clicked_on_chain){
openthedoor()}
else {
cancelBoltcutters()}
Here is the part of the code I have for now, if thats helping:
// chain mechanics
var boltcutters_used = false;
document.getElementById('item_boltcutters').onmousedown = function(){
boltcutters_used = true;
document.getElementById('item_boltcutters').style.color = "red";
document.getElementById('item_boltcutters').style.border = "1px solid red";
}
var boltcutters_found = false;
document.getElementById("chain").onmousedown = function(){
if(boltcutters_used){
alert('you open the door');
} else if(!boltcutters_found){
alert("I need to find something to break this chain...")
} else {
alert("Boltcutters could do the trick")
}
}
Thanks to the idea mentioned below I came up with following solution:
var last_clicked = null;
var test=0;
window.onclick = function (e) {
last_clicked = e.target;
if(boltcutters_used == true){
test++;
}
if(boltcutters_used == true && last_clicked !== document.getElementById("chain") && test >1){
alert("Can't use it here");
boltcutters_used = false;
test=0;
}
}
And it works :)
Maintain the last clicked item
Have a variable to store the last clicked element
On window click update the value of that variable
Check for this variable in your chain event handler
var last_clicked = null;
window.onclick = function (e) {
last_clicked = e.target;
}
var boltcutters_used = false;
document.getElementById('item_boltcutters').onmousedown = function(){
boltcutters_used = true;
document.getElementById('item_boltcutters').style.color = "red";
document.getElementById('item_boltcutters').style.border = "1px solid red";
}
var boltcutters_found = false;
document.getElementById("chain").onmousedown = function(){
if(boltcutters_used){
if(last_clicked === document.getElementById("item_boltcutters")) {
alert('you open the door');
} else {
alert("You should use the bolt cutters on this");
}
} else if(!boltcutters_found){
alert("I need to find something to break this chain...")
} else {
alert("Boltcutters could do the trick")
}
}

how to prevent tab in jquery?

can we stop prevent blur or tabbing for 5 second in input field.then after 5 second user can tab from one field to another.I use off and on function but it is not working .here is my code
http://jsfiddle.net/GV3YY/99/
$("input").off("blur");
setTimeout(function(){
$("input").on("blur");
},5000)
You need to "lock" the inputs when they is focused and use setTimeout to "unlock" it after 5 seconds. A naive implementation could look something like this: https://jsfiddle.net/my7wk6gj/2/
Update: Now pseudo prevents bluring by click. The blur still happens, but focus is returned to the original input until the 5 seconds have passed. I couldn't get event.stopImmediatePropagation to work for blur, so this is the next best thing...
var lockInput = false;
var focusTarget = null;
var lockTimeout = null;
$('input').on('focus', function (e) {
if (lockTimeout) {
return;
}
lockInput = true;
lockTimeout = setTimeout(function () { lockInput = false; lockTimeout = null }, 5000)
}).on('keydown', function (e) {
if (e.keyCode === 9 && lockInput) {
e.preventDefault();
return false;
}
}).on('blur', function (e) {
console.log('blur')
if (lockInput && focusTarget === null) {
focusTarget = e.target;
setTimeout(function () {
focusTarget.focus();
focusTarget = null;
});
}
});
The global variables are used only for the example, i'd advice against that.
Also, if you have a large number of inputs, i'd suggest using event delegation, instead of adding a listener to every one of them.

js on change event getting looped in js confirm

I have a flip toggle button().I am writing a function on change of toggle button,on change I am declaring js confirm box ,if confirms true the button remains in changed state,else it will revert in its previous state.My issue is the function is getting iterating(looping).Please suggest
To me it looks quite ok. Maybe you just forgot to encapsulate your code in $(document).ready - this is necessary because otherwise your Javascript function will be loaded before the HTML DOM has been loaded - so your function will fail to access the DOM elements.
$(document).ready(function() {
$("#btn").on("change", function() {
var txt;
var btnStatus = $("#btn").val();
console.log("btnstataus>>>>>" + btnStatus);
var r = confirm("Are you sure to change?");
if (r == true) {
if (btnStatus == "on") {
$("#btn").val("on");
} else {
$("#btn").val("off");
}
} else {
if (btnStatus == "on") {
$("#btn").val("off");
} else {
$("#btn").val("on");
}
}
});
});
Here is a working sample of your code:
https://plnkr.co/edit/AdzcN04F1fsLe9xw454j?p=preview

Can't execute a jQuery function more than once

I have the following function:
$('#edit').on("click", function () {
$('#edit').text('click1');
$('table a').click(function (e) {
e.preventDefault();
});
$('table a').css("cursor", "default");
}
});
$('#edit').click(function () {
$('#edit').unbind();
$('#edit-message-placeholder').empty();
$('#edit').text('click2');
$("table tbody").sortable("disable");
$('table a').unbind()
$('table a').css("cursor", "auto");
});
});
On first click, I want it to change the text of div#edit. On second click, it will change the text to something else. On third click, the function will behave as though it was clicked the first time.
I tried to find a solution online, but found nothing useful.
The problem is that you're approaching this incorrectly. You don't need to bind/unbind event handlers. You only need one event handler that alternates in functionality:
JavaScript
var isOkay = true;
$("p").click(function () {
if (isOkay) {
$(this).text("1st click");
} else {
$(this).text("2nd click");
}
isOkay = !isOkay;
})
HTML
<p>Click me!</p>
Every time the <p> is clicked, it performs an action and then switches the value of a boolean variable, isOkay. This means that it will alternate between the if and else block. Note that the isOkay variable is held outside the scope of the $("p").click(...) event handler.
fiddle
Try this -
Use the data property to temporarily save the counter data
<button id="edit" data-count="1">1</button>
function doWork(val){
alert(val);
};
$('#edit').on("click", function () {
if($(this).data('count') == ""){
$(this).data('count') = 1;
}
var count = parseInt($(this).data('count'));
if (count == 1){
doWork(count);
}else if (count == 2){
doWork(count);
}else if (count == 3){
doWork(count);
}
count += 1
count = count >= 4 ? 1: count;
$(this).data('count', count);
$(this).html($(this).data('count'));
});
Here is the jsfiddle - http://jsfiddle.net/pt3zE/1/

Cycle Focus to First Form Element from Last Element & Vice Versa

I have created a form with malsup's Form Plugin wherein it submits on change of the inputs. I have set up my jQuery script to index drop down menus and visible inputs, and uses that index to determine whether keydown of tab should move focus to the next element or the first element, and likewise with shift+tab keydown. However, instead of moving focus to the first element from the last element on tab keydown like I would like it to, it moves focus to the second element. How can I change it to cycle focus to the actual first and last elements? Here is a live link to my form: http://www.presspound.org/calculator/ajax/sample.php. Thanks to anyone that tries to help. Here is my script:
$(document).ready(function() {
var options = {
target: '#c_main',
success: setFocus
};
$('#calculator').live('submit', function() {
$(this).ajaxSubmit(options);
return false;
});
$(this).focusin(function(event) {
var shiftDown = false;
$('input, select').each(function (i) {
$(this).data('initial', $(this).val());
});
$('input, select').keyup(function(event) {
if (event.keyCode==16) {
shiftDown = false;
$('#shiftCatch').val(shiftDown);
}
});
$('input, select').keydown(function(event) {
if (event.keyCode==16) {
shiftDown = true;
$('#shiftCatch').val(shiftDown);
}
if (event.keyCode==13) {
$('#captured').val(event.target.id);
} else if (event.keyCode==9 && shiftDown==false) {
return $(event.target).each(function() {
var fields = $(this).parents('form:eq(0),calculator').find('select, input:visible');
var index = fields.index(this);
var nextEl = fields.eq(index+1).attr('id');
var firstEl = fields.eq(0).attr('id');
var focusEl = '#'+firstEl;
if (index>-1 && (index+1)<fields.length) {
$('#captured').val(nextEl);
} else if(index+1>=fields.length) {
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(firstEl);
} else {
event.preventDefault();
$(focusEl).focus();
}
}
return false;
});
} else if (event.keyCode==9 && shiftDown==true) {
return $(event.target).each(function() {
var fields = $(this).parents('form:eq(0),calculator').find('select, input:visible');
var index = fields.index(this);
var prevEl = fields.eq(index-1).attr('id');
var lastEl = fields.eq(fields.length-1).attr('id');
var focusEl = '#'+lastEl;
if (index<fields.length && (index-1)>-1) {
$('#captured').val(prevEl);
} else if (index==0) {
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(lastEl);
} else {
event.preventDefault();
$(focusEl).select();
}
}
return false;
});
}
});
});
});
function setFocus() {
with (document.calculator)
var recap = document.getElementById(recaptured.value);
if (recap!=null) {
setTimeout(function() {
if (recap.getAttribute('type')=='text') {
recap.select();
} else {
recap.focus();
}
}, 100 );
}
}
Edit #1: I made a few minor changes to the code, which has brought me a little closer to my intended functionality of the script. However, I only made one change to the code pertaining to the focus: I tried to to disable the tab keydown when pressed on the last element (and also the shift+tab keydown on the first element) in an attempt to force the focus on the element I want without skipping over it like it has been doing. This is the code I added:
$(this).one('keydown', function (event) {
return !(event.keyCode==9 && shiftDown==true);
});
This kind of works. After the page loads, If the user presses tab on the last element without making a change to its value, the focus will be set to the second element. However, the second time the user presses tab on the last element without making a change to its value, and every subsequent time thereafter, the focus will be set to the first element, just as I would like it to.
Edit #2: I replaced the code in Edit #1, with code utilizing event.preventDefault(), which works better. While if a user does a shift+tab keydown when in the first element, the focus moves to the last element as it should. However, if the user continues to hold down the shift key and presses tab again, focus will be set back to the first element. And if the user continues to hold the shift key down still yet and hits tab, the focus will move back to the last element. The focus will shift back and forth between the first and last element until the user lifts the shift key. This problem does not occur when only pressing tab. Here is the new code snippet:
event.preventDefault();
$(focusEl).focus();
You have a lot of code I didn't get full overview over, so I don't know if I missed some functionality you wanted integrated, but for the tabbing/shift-tabbing through form elements, this should do the work:
var elements = $("#container :input:visible");
var n = elements.length;
elements
.keydown(function(event){
if (event.keyCode == 9) { //if tab
var currentIndex = elements.index(this);
var newIndex = event.shiftKey ? (currentIndex - 1) % n : (currentIndex + 1) % n;
var el = elements.eq(newIndex);
if (el.attr("type") == "text")
elements.eq(newIndex).select();
else
elements.eq(newIndex).focus();
event.preventDefault();
}
});
elements will be the jQuery object containing all the input fields, in my example it's all the input fields inside the div #container
Here's a demo: http://jsfiddle.net/rA3L9/
Here is the solution, which I couldn't have reached it without Simen's help. Thanks again, Simen.
$(document).ready(function() {
var options = {
target: '#c_main',
success: setFocus
};
$('#calculator').live('submit', function() {
$(this).ajaxSubmit(options);
return false;
});
$(this).focusin(function(event) {
$('#calculator :input:visible').each(function (i) {
$(this).data('initial', $(this).val());
});
return $(event.target).each(function() {
$('#c_main :input:visible').live(($.browser.opera ? 'keypress' : 'keydown'), function(event){
var elements = $("#calculator :input:visible");
var n = elements.length;
var currentIndex = elements.index(this);
if (event.keyCode == 13) { //if enter
var focusElement = elements.eq(currentIndex).attr('id');
$('#captured').val(focusElement);
} else if (event.keyCode == 9) { //if tab
var newIndex = event.shiftKey ? (currentIndex - 1) % n : (currentIndex + 1) % n;
var el = elements.eq(newIndex);
var focusElement = el.attr('id');
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(focusElement);
} else if ((currentIndex==0 && event.shiftKey) || (currentIndex==n-1 && !event.shiftKey)) {
event.preventDefault();
if (el.attr('type')=='text') {
$.browser.msie ? "" : $(window).scrollTop(5000);
el.select().delay(800);
} else {
$.browser.msie ? "" : $(window).scrollTop(-5000);
el.focus().delay(800);
}
} else if (el.is('select')) {
event.preventDefault();
if (el.attr('type')=='text') {
el.select();
} else {
el.focus();
}
}
}
});
});
});
});
function setFocus() {
with (document.calculator)
var recap = document.getElementById(recaptured.value);
if (recap!=null) {
setTimeout(function() {
if (recap.getAttribute('type')=='text') {
recap.select();
} else {
recap.focus();
}
}, 1 );
}
}
I put my files available to download in my live link: http://www.presspound.org/calculator/ajax/sample.php

Categories

Resources