Why is jquery toggle not working? - javascript

I simply want to have a variable toggle between true and false and have the text on the button clicked to change as well. Here is my Jquery:
$("button").toggle(
function () {
$(this).text("Click to change to paint brush");
var erasing = true;
},
function () {
$(this).text("Click to change to eraser");
var erasing = false;
}
);
This looks 100% sound to me, but in my jsfiddle you will see that it is toggling the existence of the button before I can even click it! Why is this happening and how can I fix it?

This version of toggle has been deprecated (1.8) and removed (1.9). Now you need to handle it in button click itself.
Somthing like this:
var erasing = false;
$("button").click(function () {
erasing = !erasing;
$(this).text(function (_, curText) {
return curText == "Click to change to paint brush" ? "Click to change to eraser" : "Click to change to paint brush" ;
});
console.log(erasing);
});
Fiddle
Plus if you want to preserve the value of the variable just define them out of the click event scope, so that it is more global to be accessed outside.
See
.toggle
.text(func) syntax
Deprecated toggle

Thank you all for explaining how toggle is out of date...so that is all I needed and then I solved my problem with a simple if statement:
var erasing = false;
var i = 0
$("button").click(function () {
if(i%2==0){
$(this).text("Click to change to paint brush");
erasing = true;
}
else{
$(this).text("Click to change to eraser");
erasing = false;
};
i += 1
});
jsfiddle

As PSL said, the toggle you're looking for is gone and lost. if you want a click and hold solution (as your title suggests), you could look at using mouseup and mousedown.
var erasing;
$("button").on({
"mousedown": function () {
$(this).text("Click to change to paint brush");
erasing = true;
},
"mouseup mouseleave": function () {
$(this).text("Click to change to eraser");
erasing = false;
}
});
Demo : http://jsfiddle.net/hungerpain/ymeYv/6/

Related

jquery. something wrong with syntax?

$('#buttons1').on('click', function(event) {
$('#button1content').toggle('show');
var wasVisible = $("#button1content").is(":visible");
if(!wasVisible) {
$("#buttons1").css("opacity", "0.5");
}
});
Toggle works perfectly fine, but whatever is inside the if statement doesn't get executed when #button1content is no longer visible. boo. It could be another part of my code that is messing it up, but I only want to know if there is anything wrong with this.
your variable wasVisible will always return a true
you can place the toggle on the last part.
you can reorder your code like this.
$('#buttons1').on('click', function(event) {
var wasVisible = $("#button1content").is(":visible");
if(!wasVisible) {
$("#buttons1").css("opacity", "0.5");
}
$('#button1content').toggle('show');
});
JSFIDDLE DEMO
OR
just simply remove the 'show' on the toggle just use
$('#button1content').toggle();
like this:
$('#buttons1').on('click', function(event) {
$('#button1content').toggle();
var wasVisible = $("#button1content").is(":visible");
if(!wasVisible) {
$("#buttons1").css("opacity", "0.5");
}
});
JSFIDDLE DEMO
The if statement is not reachable because you always showed button1content
$('#button1content').toggle('show');
So var wasVisible = $("#button1content").is(":visible"); will always result to true

2 anchor with one click

So here is my code
prev
prev
How do I make it both click if I click any of it ?
If I click .slider-1-prev, at the same I click .slider-2-prev
If I click .slider-2-prev, at the same I click .slider-2-prev
How to make it by javascript ?
As well as triggering the event on the other link, you need to shield against infinite repeating (e.g. with a shield variable):
var inClick = false;
$(document).ready(function {
$('.slider-1-prev').on('click', function {
if (!inClick) {
inClick = true;
$('.slider-2-prev').trigger('click');
inClick = false;
}
});
$('.slider-2-prev').on('click', function {
if (!inClick) {
inClick = true;
$('.slider-1-prev').trigger('click');
inClick = false;
}
});
})
If you want a shorter version, you can listen for both on one handler and click "the other":
var inClick = false;
$(document).ready(function {
var $sliders = $('.slider-1-prev,.slider-2-prev');
$sliders.on('click', function {
if (!inClick) {
inClick = true;
// Click the one that was not clicked (not this)
$sliders.not(this).trigger('click');
inClick = false;
}
});
})
Another option is a bit more complicated as you need to turn the handler off and then on again. Stick with this simple one for now.
The on/off approach involves disabling the handling while executing it, so that it will not trigger again until you reconnect it. The downside is you need to reference a separate function so that it can effectively reference itself:
$(document).ready(function {
var $sliders = $('.slider-1-prev,.slider-2-prev');
// Define separate named function
var clickTheOtherOne = function(){
// Disable the click
$sliders.off('click');
// Click the one that was not clicked (not this)
$sliders.not(this).trigger('click');
// Reenable the click handler
$sliders.on('click', clickTheOtherOne);
}
// Initial enabling of the handler
$sliders.on('click', clickTheOtherOne);
});
If they're going to behave the same, why not define only one function for both?
$('.slider-1-prev, .slider-2-prev').click(function(){
//... mutual code
});
I can't figure why you need to do what you ask, but try this approach:
js code:
// this will work on all classes that start with 'slider-prev'
$('*[class^="slider-prev"]').on('click',function{
// do something
});
Of course you will need to alter your htm code to:
prev
prev
this should do the trick
$(document).ready(function{
$('.slider-1-prev').on('click',function{
$('.slider-2-prev').trigger('click');
});
$('.slider-2-prev').on('click',function{
$('.slider-1-prev').trigger('click');
});
})
Try this -
$('.slider-1-prev').click(function(){
$('.slider-2-prev').trigger('click');
});
// If you need the opposite, then do -
$('.slider-2-prev').click(function(){
$('.slider-1-prev').trigger('click');
});

Hack: Disable click click with jQuery

I'm hacking a gallery plugin where I want to disable the click event for the thumbnail and replace it with a hover event.
This is what I did: http://jsbin.com/enezol/3
$(function() {
var galleries = $('.ad-gallery').adGallery();
$('.ad-thumb-list a').hover(function() {
$(this).click();
});
$('.ad-thumb-list a').click(function() {
return false;
});
});
The plugin doesn't allow me to set event to use. So Instead of changing it from their code, I'll just add a little tweak on top of it.
So I want to disable the click event for the 'thumbnail' and just use 'hover' event instead.
Any got and ideas? I'm also open to other approach as long as it meets my requirement.
Thank You!
Trying to implement Steph Skardal and Nicosunshine suggestion:
var thumbs = $('.ad-thumb-list a'),
oldfunction = thumbs.data("events").click["function () { context.showImage(i); context.slideshow.stop(); return false; }"];
thumbs.unbind("click").hover(oldFunction);
edit: My Solution:
I use return false to restrict it from going to the url but it does not restrict in calling the function. Any alternative ideas?
var galleries = $('.ad-gallery').adGallery();
var thumbs = $('.ad-thumb-list a');
thumbs .hover(
function () {
$(this).click();
},
function () {
}
);
thumbs.click( function () { return false; });
You want to use jQuery's unbind method, to unbind the click event. It will have to be called after the plugin is called. E.g.:
$('.ad-thumb-list a').unbind('click');
You could try to unbind the click method and then bind the original function to the hover.
If you can't get the original function you can get it by seeing what the console returns if you throw:
$('.ad-thumb-list a').data("events").click; //name of the property that has the function
then you grab that function and do:
var thumbs = $('.ad-thumb-list a'),
oldfunction = thumbs.data("events").click["theValueYouGotInTheConsole"];
thumbs.unbind("click")
.hover(oldFunction);
Edit:
Here is an example of what I ment with "theValueYouGotInTheConsole", in the image I'm accessing the click property, and then the "4" is where the function is stored.
If you don't want to hardcode the value you can do:
var dataEvents = thumbs.data("events").click,
oldFunction;
for(var functionEvent in dataEvents) {
oldFunction = dataEvents[functionEvent];
break; //I'm assuming there's only one event
}

Improve This: Change button text/background onmousedown - revert onmouseup

I would like to see if anyone in the community can improve on this code.
GOAL: The application is full of input elements that are styled up to look like custom buttons. They are of various types e.g. 'submit', 'reset' and 'button'. When the user hits the button (i.e. clicks it with their mouse on PC or touches the screen on the right place on a touch-screen device e.g. BlackBerry) the button text and background should change to indicate the button has been pushed. The text and background should revert before the action associated with the button is executed - to indicate the button has been released.
Here is the snippet of the code that I have for my solution - can anyone see ways to improve/slim/refactor?
<script type="text/javascript">
$(document).ready(function () {
RegisterJQueryFunctions();
});
</script>
In an external file:
function RegisterJQueryFunctions() {
$('input[type=submit], input[type=button], input[type=reset]').mousedown(function () {
// Record the original font and BG colors so we can revert back to them in 'delight'
var originalFont = $(this).css("color");
var originalBG = $(this).css("background-color");
$(this).data("originalFont", originalFont);
$(this).data("originalBG", originalBG);
$(this).highlightBG();
$(this).highlightFont();
});
$('input[type=submit], input[type=button], input[type=reset]').mouseup(function () {
$(this).revertFont();
$(this).revertBG();
});
$.fn.highlightFont = function (highlightFontColor) {
var highlightFont = highlightFontColor || "#FFFFFF"; // Defaults to white
$(this).css("color", highlightFont);
};
$.fn.highlightBG = function (highlightBGColor) {
var highlightBg = highlightBGColor || "#FF7F00"; // Defaults to orange
$(this).css("background-color", highlightBg);
};
$.fn.revertFont = function () {
var originalFont = $(this).data("originalFont");
if (!originalFont.length)
originalFont = "#000000"; // Defaults to black in case data attribute wasn't set properly in highlightFont
$(this)
.css("color", originalFont);
};
$.fn.revertBG = function () {
var originalBG = $(this).data("originalBG");
if (!originalBG.length)
originalBG = "#FEC800"; // Defaults to orange in case data attribute wasn't set properly in highlightFont
$(this)
.css("background-color", originalBG);
};
}
This is how you would do it with CSS. If you want the pressed look to be the following CSS
.pressed { color : #ffffff; background-color : #FEC800; }
Then your functions are simple:
function RegisterJQueryFunctions() {
$('input[type=submit], input[type=button], input[type=reset]')
.mousedown(function () { $(this).toggleClass("pressed",true); })
.mouseup(function () { $(this).toggleClass("pressed",false); });
}
You can have different pressed looks for different input types (using standard CSS selectors).
You are separating the styling from the code (always a good thing.)
Using CSS (class), you can reduce the size of your code drastically. Secondly CSS will give the option of changing colors without altering your javascript (Themes). The sole purpose of CSS is to give look and feel to the site & for javascript, add dynamic behavior to the site.
Hope this helps.
If you're using the same jQuery selector several times you should cache the
first jQuery object returned and reuse it
If you're calling several jQuery methods on the same jQuery object you can chain them
I dislike single-use variables: if a variable is only assigned a value in one
place and that value is only used in one (other) place then you don't need it
If setting more than one value with .data() (or .attr() or in several other jQuery methods) you can do all with a single call by putting the properties in a map
So:
function RegisterJQueryFunctions() {
$('input[type=submit], input[type=button], input[type=reset]').mouseup(function () {
$(this).revertFont().revertBG();
})
.mousedown(function () {
// Record the original font and BG colors so we can revert back to them in 'delight'
var $this = $(this);
$this.data({"originalFont" : $this.css("color"),
"originalBG" :, $this.css("background-color")
})
.highlightBG()
.highlightFont();
});
$.fn.highlightFont = function (highlightFontColor) {
$(this).css("color", highlightFontColor || "#FFFFFF");// Defaults to white
};
$.fn.highlightBG = function (highlightBGColor) {
$(this).css("background-color", highlightBGColor || "#FF7F00";);
};
$.fn.revertFont = function () {
var $this = $(this);
// Defaults to black in case data attribute wasn't set properly in highlightFont
$this.css("color", $this.data("originalFont") || "#000000");
};
$.fn.revertBG = function () {
var $this = $(this);
// Defaults to orange in case data attribute wasn't set properly in highlightFont
$this.css("background-color", $this.data("originalBG") || "#FEC800");
};
}
Using a combination of the above advice, this is the solution is ended up with:
$('input[type=submit], input[type=button], input[type=reset]')
.mousedown(function () { $(this).toggleClass("pressed", true); })
.mouseup(function () { $(this).toggleClass("pressed", false); })
.focusout(function () { $(this).toggleClass("pressed",false); });
$('a,a>*')
.mousedown(function () { $(this).toggleClass("pressed",true); })
.mouseup(function () { $(this).toggleClass("pressed", false); })
.focusout(function () {
$(this).toggleClass("pressed", false);
$(this).children().toggleClass("pressed", false); // call explictily because some elements don't raise the 'focusout' event
});

jQuery changing an image on hover, then maintain image on click

I'm at a bit of a problem with jQuery and an image.
I'm trying to create a simple system where an image changes on hover (which I've successfully made work with jQuery .hover()) however I'm now trying to set it up so if the user clicks on the image, the source is permanently changed to the hover image.
The problem I'm having is when I click, the source changes but when I hover off it changes back to the "off" image! Such a simple problem but I can't find a solution.
The hover code:
$("#image").hover(function () {
$(this).attr("src", getImageSourceOn("image"));
}, function () {
$(this).attr("src", getImageSourceOff("image"));
});
The functions getImageSourceOn / Off simply return a string based on the parameter with the new source.
The onClick code:
var imageSource = $(imageID).attr("src");
var onOff = imageSource.substring((imageSource.length - 5), (imageSource.length - 4));
if (onOff == "F")
{
//alert("Off\nstrID = " + strID);
$(imageID).attr("src", getImageSourceOn(strID));
}
else
{
//alert("On");
$(imageID).attr("src", getImageSourceOff(strID));
}
This code just takes the source and looks for On / Off within the source to put the opposite as the image. I tried using .toggle() instead of this substring method but I couldn't get it to work.
Declare a global variable. Attach a function on the click event:
var clicked = false;
$("#image").click(function(){
if(!clicked)
clicked = true;
else
$(this).attr("src", getImageSourceOff("image"));
});
Then modify you hover code
$("#image").hover(function () {
$(this).attr("src", getImageSourceOn("image"));
}, function () {
if(!clicked)
$(this).attr("src", getImageSourceOff("image"));
});

Categories

Resources