I'm trying to execute a function twice, and I can't figure out what I'm doing wrong. JSFiddle here: http://jsfiddle.net/g6PLu/3/
Javascript
function truncate() {
$(this).addClass('closed').children().slice(0,2).show().find('.truncate').show();
}
$('div').each(truncate);
$('.truncate').click(function() {
if ($(this).parent().hasClass('closed')) {
$(this).parent().removeClass('closed').addClass('open').children().show();
}
else if ($(this).parent().hasClass('open')) {
$(this).parent().removeClass('open').addClass('closed');
$('div').each(truncate);
$(this).show();
}
});
The problem is on line 15, where I call $('div').each(truncate); the second time. For some reason it doesn't seem to be executing. Any ideas?
I think you are overcomplicating a simple task. I'd take advantage of the classes to show/hide stuff with CSS (you're adding the classes but not using them!).
Check out this simpler version:
Relevant CSS
.closed p { display: none; }
.closed p:nth-child(2) { display: block; }
JS
$('div').addClass('closed');
$('.truncate').click(function() {
$(this).closest('div').toggleClass('closed');
});
http://jsfiddle.net/g6PLu/9/
When you call show, the <p> changes to <p style="display: block; "> that's why, you need to call hide or remove that style part
is this the spected behavior?
else if ($(this).parent().hasClass('open')) {
$(this).parent().removeClass('open').addClass('closed').children().hide();
$('div').each(truncate);
$(this).show();
}
Related
I want to use just ONE button to control Opening and Closing an Off-Canvas Menu. So I created a Button with OpenButton class which open menu, after clicking, I remove OpenButton class and add CloseButton class, These all work like a charm, But When I call Click Event on CloseButton It doesn't work, What is the problem ?
This is my code :
$('.OpenButton').click(function() {
$(this).addClass('CloseButton');
$(this).removeClass('OpenButton');
});
$('.CloseButton').click(function() {
alert('Close');
});
Since you're adding the class dynamically, you need to use event delegation to register the same with the event handler mechanism,
$(document).on('click', ".CloseButton", function() {
alert('Close');
});
Hope this helps!
That is because the click event is bound at runtime. Since .CloseButton does not exist when the code is executed, no click event will be bound to it. One solution is to use $(document).on('click', '.CloseButton', function() {...}) to do that, but that is considered resource intensive and unnecessarily heavyhanded.
I would recommend that you do not change the class of the button instead. If you want to modify the style or appearance of the button when it's open/close, you can do it by adding classes instead of swapping classes, for example:
$('.button').click(function() {
$(this).toggleClass('is-open');
});
In this case, you can you also store the state of the button in jQuery's data object. That will abstract reading the state of an object from the DOM based on it's class:
$(function() {
$('.button').click(function() {
// Store state
if ($(this).data('is-open')) {
$(this).data('is-open', false);
alert('closing!');
} else {
$(this).data('is-open', true);
alert('opening!');
}
// Toggle class
$(this).toggleClass('is-open');
$('.toggleTarget').toggleClass('is-hidden');
});
});
.is-hidden {
display: none;
}
.button {
background-color: steelblue;
color: #fff;
display: inline-block;
padding: 10px;
}
.button.is-open {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Toggle
<div class="toggleTarget is-hidden">I am content that is toggled.</div>
I am trying to apply starts with function on textarea, but obviously I am doing something wrong. I don't understand javascript, so I am sorry for obvious mistakes or problems. At least I tried what seemed logical to me... Fiddle here: http://jsfiddle.net/SVxbW/235/
HTML:
$("textarea").bind(function () {
if ($(this).startsWith("Hello") {
$(".kuk").show();
}
else {
$(".kuk").hide();
}
});
.kuk {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<textarea></textarea>
<button class="kuk">Clear</button>
And what if someone pastes the text "Hello" with right click of mouse? How to recognize that action too?
You need to get the val() then use startsWith(). Additionally you need to bind proper event handler. Here I have used keyup
$("textarea").on('keyup', function() {
if ($(this).val().startsWith("Hello")) {
$(".kuk").show();
} else {
$(".kuk").hide();
}
});
Updated Fiddle
Try this. You need to bind an event also you need to get val to check whether it startswith hello or not.
$("textarea").bind('keyup',function () {
if ($(this).val().startsWith("Hello")) {
$(".kuk").show();
}
else {
$(".kuk").hide();
}
});
Here is jsfiddle
I made jsfiddle for those wondering which code I am using right now. I added few kinds of input options and now it works in chrome as well.
final fiddle
$("textarea").bind('change keyup paste blur input',function () {
if ($(this).val().startsWith("Hello") || $(this).val().startsWith("HELLO") || $(this).val().startsWith("hello")) {
$(".kuk").show();
}
else {
$(".kuk").hide();
}
});
This question already has answers here:
Jquery Toggle two function not work in 1.10.1
(7 answers)
Closed 9 years ago.
I would like to update my website to jQuery 1.10 but I use a function with the deprecated toggle().
I remember, I was having a hard time to make this function works in first time, does it exists a function that could replace the toggle() without changing all the code.
I am not a jQuery expert and help would be appreciated.
css:
fieldset.collapsed * {
display: none;
}
fieldset.collapsed h2, fieldset.collapsed {
display: block !important;
}
fieldset.collapsed h2 {
background-image: url(../img/nav-bg.gif);
background-position: bottom left;
color: #999;
}
fieldset.collapsed .collapse-toggle {
background: transparent;
display: inline !important;
}
jquery:
var sPath=window.location.pathname;
(function ($) {
$(document).ready(function () {
function show () { // Show
$(this).text(gettext("Hide"))
.closest("fieldset")
.removeClass("collapsed")
.trigger("show.fieldset", [$(this).attr("id")]);
window.localStorage.setItem($(this).attr("id"), true);
}
function hide () { // Hide
$(this).text(gettext("Show"))
.closest("fieldset")
.addClass("collapsed")
.trigger("hide.fieldset", [$(this).attr("id")]);
window.localStorage.removeItem($(this).attr("id"))
return false;
}
// Add anchor tag for Show/Hide link
$("fieldset.collapse").each(function (i, elem) {
// Don't hide if fields in this fieldset have errors
key = 'fieldsetcollapser' + i + sPath;
if (typeof (window.localStorage) != 'undefined') {
var item = $(elem)
.addClass("collapsed")
.find("h2")
.first()
.append(' (<a id=' +
key +
' " class="collapse-toggle" href="#">' +
gettext("Show") +
'</a>)'
).find('a');
if (window.localStorage.getItem(key)) {
//alert('show')
show.apply(item);
$(item).toggle(hide, show);
}else {
if ($("ul.errorlist").length >0) {
//alert('yo show')
show.apply(item);
$(item).toggle(hide, show);
}else{
$(item).toggle(show, hide);
//alert("hide")
}
}
} else {
throw "window.localStorage, not defined";
}
});
});
EDITED:See how it works here (working with jQuery 1.6)
The reason that the .toggle() function was deprecated was because of confusion just like this!
What's going on is that your code is calling (on an alternating basis) your own internal "hide" and "show" functions. The .toggle(hide,show) call takes care of that for you.
However, inside of your hide() and show() functions, you're not actually hiding or showing anything. What you're doing is adding or removing a class, which may or may not hide or show something.
The solution
The only solution to alternatively call these two functions is to change the 'click' event each time one of those functions is called.
At the bottom of your show() code, you need to add:
$(this).one("click", hide);
At the bottom of your hide() code, you need to add:
$(this).one("click", show);
Finally, you need to replace your calls to .toggle() with these calls:
$(item).one("click", hide); // replaces $(item).toggle(hide,show);
$(item).one("click", show); // replaces $(item).toggle(show,hide);
Why not .is(":visible")?
Quite simply, the class that you are adding/removing is the "collapsed" class. This class does not actually hide the $(item). Because of this the $(this).is(":visible") will always be true!
Clearly, that won't work.
Here is a demonstration that illustrates the point: JSFiddle
Fully in code
For those who like to read code instead of words:
function firstEvent() { // e.g. "hide"
//First event code
$(item).one("click", secondEvent);
}
function secondEvent() { // e.g. "show"
//Second event code
$(item).one("click", firstEvent);
}
$(item).one("click", firstEvent); // replaces $(item).toggle(firstEvent, secondEvent);
I would replace your instances with an if statement
$(item).click(function(){
if ($(this).is(':visible')) {
$(this).hide();
}
else {
$(this).show();
}
});
Here is a demo of my above code working using a p element and an img.
DEMO http://jsfiddle.net/kevinPHPkevin/8TFFx/
You could also do it by using CSS/Jquery
$('p').click(function(){
if ($('img').is(':visible')) {
$('img').css("display","none");
}
else {
$('img').css("display","block");
}
});
I have a button on my site that has jquery that changes some css of other elements on click.
I want to assign another function to reverse the css changes when the button is clicked a second time.
$('.mobileitem').click(function(){
$('.bottomfooter').css("bottom","75px");
$('#mobilefoot').css("display", "block");
});
I want to be able to click .mobileitem again and have the css change to bottom:0 display:none for their respective elements.
Each time I click the .mobileitem it should go between the two.
I think it is .toggle() but not sure of the proper syntax or if there is a better way
$('.mobileitem').click(function(){
var bot_val="75px";
var dis_val="block";
if($('.bottomfooter').css("bottom")==bot_val){
bot_val="0px";
}
if($('#mobilefoot').css("display")==dis_val){
dis_val="none";
}
$('.bottomfooter').css("bottom", bot_val);
$('#mobilefoot').css("display", dis_val);
});
This should work!
Try this
function toggleClickEvents(item, click1, click2){
$(item).off('click').on('click', function(){
click1();
toggleClickEvents(item, click2, click1);
});
}
Or just use .toggle() although it is deprecated and possibly removed. (Not sure what the replacement is)
$('.mobileitem').toggle(function(){
$('.bottomfooter').css("bottom","75px");
$('#mobilefoot').css("display", "block");
}, function(){
$('.bottomfooter').css("bottom","0px");
$('#mobilefoot').css("display", "none");
});
Here's a neater, cleaner example using TOGGLE functionality.
It'll work as well. :)
you can write two css classes
.bottom75
{
bottom: 75px;
display: block;
}
.bottom0
{
bottom: 0px;
display: none;
}
On click event
$('.mobileitem').click(function(){
$(this).hasClass('bottom75') ? $(this).addClass('bottom0'): $(this).addClass('bottom75');
});
try this:
$('.mobileitem').click(function(){
$(".bottomfooter, #mobilefoot").toggle(function() {
$('.bottomfooter).css('bottom','75px');
$('#mobilefoot').css('display', 'block');
}, function () {
$('.bottomfooter').css('bottom','0');
$('#mobilefoot').css('display', 'none');
});
});
<div class="example">
Test
</div>
$('.example').click(function(){
$(this).css('color','red');
});
When the code above get's clicked, it will apply the .css. Now what I need is for another bit of code (let's say $(this).css('color','blue');) to be applied, replacing the previous code when .example gets clicked a second time.
I've searched for this and askers seem to only need .show/.hide events which can be substituted with .toggle, which is obviously not the case here.
Since you may have many instances of class example, simply maintaining a state using a single variable is not feasible, what you can do is to maintain the state of each instance of example within itself:
Define two css classes
.example { background:blue }
.example.red { background:red }
Then your click method:
$('.example').click(function(){
$(this).toggleClass('red');
});
If you prefer not to define new css classes, you can use data(), to make sure that the state is exclusive within each .example, this is useful if you have many instances of .example
$('.example').click(function() {
var color = $(this).data('color');
if(color != 'blue') {
$(this).css('color', 'blue');
$(this).data('color', 'blue');
} else {
$(this).css('color', 'red');
$(this).data('color', 'red');
}
});
http://api.jquery.com/data/
Something like this would work to toggle between 2 colours (or styles).
$('.example').click(function(){
if($(this).css('color') == "red")
{
$(this).css('color','blue');
}
else
{
$(this).css('color','red');
}
});
<div class="example">
Test
</div>
just maintain a bool and you are done..
var isRed=false;
$('.example').click(function(){
if(isRed)
{
$(this).css('color','blue');
isRed=false;
}
else
{
$(this).css('color','red');
isRed=true;
}
});
Use addClass and removeClass
.blueColor
{
background-color: blue;
}
.redColor
{
background-color: red;
}
And use in your javascript the addClass and removeClass functions:
<script>
$(document).ready(function(){
$(".example").keypress(function() {
if($(".example").val().length > 0)
{
$(".example").addClass("redColor");
}
else {
if($(".example").val().length == 0)
{
$(".example").addClass("blueColor");
$(".example").removeClass("redColor");
}
}
});
});
</script>
I guess you need something more generic about click event exactly so I'd suggest you to use data method to leave the flags
$('.example').click(function() {
if (!$(this).data("custom-even")) {
// odd execution
$(this).data("custom-even", true)
} else {
// even execution
$(this).data("custom-even", false)
}
});
$('.example').click(function(){
var theExample = $(this);
if(theExample.hasClass("clicked")){
theExample.css('color','blue').removeClass("clicked");
}else{
theExample.css('color','red').addClass("clicked");
}
});
http://jsfiddle.net/SnDgh/
Hiya Try this with toggle :)) http://jsfiddle.net/FVXAZ/
SO you can use toggle with your css and every second click will have the vice-a-versa affect. :)
Code
$(function() {
$('.example').toggle(function() {
$(this).css('color','red');
}, function() {
$(this).css('color','blue');
});
});
Have a nice man man, cheers!
Try this:
$('.example').click(function(){
if($('.example').data('isAlreadyClicked')=='true')
{
$(this).css('color','blue');
$('.example').data('isAlreadyClicked','false')
}
else
{
$(this).css('color','red');
$('.example').data('isAlreadyClicked','true')
}
});
Use the one method to handle one-time event binding is a good choice, however this solution will stop all events binded after this code, it may cause inconsistency.
$('.example')
.one('click', function(e) {
e.stopImmediagePropagation();
})
.on('click', function() {
$(this).css('color', blue');
});
Lot of answers all defining a single solution.
Basically, there are two ways that you should use. The other ways mentionned are either unperformant or unsemantic (using data for this kind of solution is overkill). Here are the two ways you may use:
// Toggle a class 'red' defined in your stylesheet
$('.example').on('click', function() {
$(this).toggleClass('red')
})
// Toggle the color with an "if" check
$('.example').on('click', function() {
if (this.style.color === 'red') { // using jQuery is not required
this.style.color === 'blue'
}
else {
this.style.color === 'red'
}
})
You can write:
$('#id').toggle(function() {
$('.css').css('color','red');}
,function() { /////////the second click
$('.css').css('color','blue');}
);