jQuery click event seems to be kind of late - javascript

I'm working on a Facebook reaction bar so it is pretty hard to copy the code here because it has a lot of events binded but all of you got facebook so if you want to check it by yourself - please do it.
The thing is that I managed to move the reaction bar under the react root and now I wanted to make the clicked reaction counter change the background color of itself to green.
And everything is working almost good excluding one thing: it is one click behind. To make you understand better I recorded little example how it looks. The red pulse ring appears when I click: https://vid.me/HqYp
Here is the changing code:
$(this).find('div._iu-[role="toolbar"]').bind('click',function(){
$(this).find('p.counter').each(function(){$(this).css('background-color','#48649F');});
$(this).find('span[aria-pressed="true"]').find('p.counter').css('background-color','green');
});
$(this) is div[id*="post"] so in $(this) I'm getting div with the whole post.
I thought that maybe I should use a callback function after changing-every-counter-to-default-color function but I don't know am I right and if it's right solution.
Thanks from above. (:

You can probably simplify this a bit. Although without the html structure I can't know for sure how the layout of the function works with respect to the event origin. Also I am not sure when the aria-pressed is set to true so I made the function a bit more generic. You simply add a data attribute to target the span you want to be targeted by the click.
<div class="_lu-" role="toolbar" data-target=".facebook-counter">
Later in your javascript you do the following
var $t = $(this);
var $t.target = $(this).data('target');
$t.on('click','div._lu-[role="toolbar"]', function() {
$t.find($t.target).css({
'background-color':'green'
}).siblings().css({'background-color','#48649F'});
});
This code is assuming first that your spans are in the same container, and second that the first $(this) refers to the parent container of this whole toolbar, and last that you have put data-target="" attributes with selectors for the appropriate target you want to affect.
This is a sample:
$(document).ready(function(){
$('.toolbar').on('click','.toolbar-item .icon', function(event) {
event.preventDefault();
event.stopPropagation();
if(!this.$) this.$ = $(this);
if(!this.parent) this.parent = this.$.parent();
if(!this.counter) this.counter = this.$.siblings('.counter');
this.parent.addClass('selected').siblings('.selected').removeClass('selected');
var count = this.counter.data('value');
count++;
this.counter.data('value',count);
this.counter.html(count);
});
});
.toolbar {
font-size:0;
text-align:center;
}
.toolbar-item .icon {
background:#FFF;
padding:30px;
border:1px solid #AAA;
border-radius:100%;
margin:0 20%;
transition:0.8s ease all;
}
.selected .icon {
background:#369;
}
.toolbar-item .counter {
background:#E0E0E0;
margin:0 10px;
transition:0.4s ease background;
}
.selected .counter {
background:#509050;
}
.toolbar-item {
font-size:10pt;
width:25%;
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="toolbar">
<div class="toolbar-item">
<div class="icon">Like</div>
<div class="counter" data-value="0">0</div>
</div>
<div class="toolbar-item">
<div class="icon">Wow</div>
<div class="counter" data-value="0">0</div>
</div>
<div class="toolbar-item">
<div class="icon">Sad</div>
<div class="counter" data-value="0">0</div>
</div>
<div class="toolbar-item">
<div class="icon">Angry</div>
<div class="counter" data-value="0">0</div>
</div>
</div>

As of jQuery 1.7 they introduced the .on('click', function().... method. Try that instead and see if you get the same results.

Quick answer without having tested or the time to test your code. I recently had a performance issue with a nested function, so maybe look at that second line with the .each() method.

Related

Can't hide other elements while clicking on another

I'm trying to make a toggle which works, but every element I click on creates a stack of these showed elements. Instead I'm trying to hide everything and display only element that I clicked on. Now I can only hide it when I click on the same element twice, which is not what I want. I want to click on one and hide previous ones that were showing.
.totalpoll-choice-image-2 is a bunch of images that always has to be shown. They are what the user clicks on to display hidden description under each image. That description shows up when I click on .totalpoll-choice-image-2. There are 5 images with that class. The next image I click on, I want to hide the previous description box.
My code:
jQuery(document).ready(function() {
var element = document.getElementsByClassName("totalpoll-choice-image-2");
var elements = Array.prototype.slice.call(Array.from( element ) );
console.log(elements);
jQuery(element).each(function(item) {
jQuery(this).unbind('click').click(function(e) {
e.stopPropagation();
var id = jQuery(this).attr("data-id");
console.log(this);
//jQuery("#" + id).css({"display": 'block !important'});
//document.getElementById(id).style.setProperty( 'display', 'block', 'important' );
var descriptionContainer = document.getElementById(id);
var thiss = jQuery(this);
console.log(thiss);
console.log(jQuery(descriptionContainer).not(thiss).hide());
jQuery(descriptionContainer).toggleClass("show");
});
})
})
You can attach event handlers to a group of DOM elements at once with jQuery. So in this case, mixing vanilla JS with jQuery isn't doing you any favors - though it is possible.
I threw together this little example of what it sounds like you're going for.
The script itself is very simple (shown below). The classes and IDs are different, but the idea should be the same:
// Assign click handlers to all items at once
$('.img').click(function(e){
// Turn off all the texts
$('.stuff').hide();
// Show the one you want
$('#' + $(e.target).data('id')).show();
})
https://codepen.io/meltingchocolate/pen/NyzKMp
You may also note that I extracted the ID from the data-id attribute using the .data() method, and attached the event listener with the .click() method. This is the typical way to apply event handlers across a group of jQuery objects.
From what I understood based on your comments you want to show only description of image that has been clicked.
Here is my solution
$('.container').on('click', 'img', function() {
$(this).closest('.container').find('.image-description').addClass('hidden');
$(this).siblings('p').removeClass('hidden');
});
https://jsfiddle.net/rtsj6r41/
Also please mind your jquery version, because unbind() is deprecated since 3.0
You can use event delegation so that you only add your event handler once to the parent of your images. This is usually the best method for keeping work the browser has to do down. Adding and removing classes is a clean method for show and hide, because you can see what is happening by looking at your html along with other benefits like being easily able to check if an item is visible with .hasClass().
jsfiddle: https://jsfiddle.net/0yL5zuab/17/
EXAMPLE HTML
< div class="main" >
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="clear">
</div>
</div>
EXAMPLE CSS
.image-parent{
height: 100px;
width: 200px;
float: left;
margin: 5px;
}
.image-parent .image{
background: blue;
height: 50%;
width: 100%;
}
.image-descr{
display: none;
height: 50%;
width: 100%;
}
.show-descr{
display: block;
}
.clear{
clear: both;
}
EXAMPLE JQUERY
$(".main").on("click", ".image-parent", ShowDescription);
function ShowDescription(e) {
var $parent = $(e.target).parent(".image-parent");
var $desc = $parent.find(".image-descr");
$(".image-descr").removeClass("show-descr");
$desc.addClass("show-descr");
}

Jquery will not select button after class has been toggled

I have some jquery that will, when a button is clicked, switch a class from a button to a different class (i.e. on click switch class from #testButton from .first to .second with an image toggle to show it works). The first click works well and it toggles the image, but the second click does not do anything. It seems as if it is not recognizing the new class. Here is a fiddle.
https://jsfiddle.net/myfb44yu/
This is the problematic javascript.
$(document).ready(function(){
$('.first').click(function(){
alert('works');
$('#testButton').toggleClass('first', 'second');
});
$('.second').click(function(){
alert("works");
$('#testButton').toggleClass('second', 'first');
});
});
The interesting thing is that it works when I use an alert() to check but not when I try to change an img src.
Your main issue here is a syntax error in regards to your .toggleClass, but seeing as others have addressed that, I'd like to point out that you should consider re-thinking how you apply your listeners - just as good habit moving forward.
An overview of jQuery Event Bindings
Think of the elements on your page as items in a store. You're an employee, and your manager says "Go put a red tag on anything in the toys department", and so you do. The next day, he puts 10 new toys in the toy department, and says to you "Why don't all the toys have red tags on them?" He then moves one of the toys to the clothing section and asks you, "Why does this item have a red tag on it?" It's simple. You put the red tags on anything in the toys department when he told you to do it - things got moved around afterwards.
The toys in this example would be your .first and .second elements.
This is how jQuery event bindings work - they only apply to elements that satisfied the selector at the time the event was initialized.
So, if you do $('.myClass').click();, then put .myClass on five buttons - none of those buttons will call this function, as they didn't have listeners put on them.
Similarly, if you put a listener on an element using class, but then remove the class from that element, it will maintain the bound event.
The Solution
$(document).on("click", ".first", function() { } );
This is known as event delegation.
In continuing with my analogy from before, this would be the equivalent of skipping tagging the items altogether, and instead just deciding whether or not they're a toy when the customer brings them to the cash register.
Instead of putting the listener on specific elements, we've put it on the entire page. By using ".first" as the second parameter (which takes a selector), the function will only be executed if the element has class first.
Hope this helps.
EDIT: As I was typing, JHecht left a good answer that points out the same issue I outlined above.
N number of elements can have the same class name ,so that's the reason if your trying to search it as $('.classname') returns an array ,so that's the reason your code is not working.class selector
Id is unique,each element should have a single id . In your code button has two id's and for the same button your trying to toggle first and second,you need not have two separate events for first and second
instead you can write as following
check this snippet
$(document).ready(function() {
var firstElements = $('.first')
var first = firstElements[0];
var secondElements = $('.second');
var second = secondElements[0]
$("#testButton").click(function() {
alert('works');
$(this).toggleClass('first').toggleClass('second');
});
});
.first {
color: red;
}
.second {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="img/images.jpeg" alt="" id="testImage">
<div id="testDiv">
<button type="button" id='testButton' class='first'>Hi</button>
</div>
Hope it helps
Ho about this solution. Hope it helps!
$(document).ready(function(){
$("#testButton").click(function(){
if($(this).prop("class") === "first"){
alert('first');
$(this).removeClass("first").addClass("second");
}
else if($(this).prop("class") === "second"){
alert("second");
$(this).removeClass("second").addClass("first");
}
});
});
.first{
color: red;
}
.second{
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<img src="img/images.jpeg" alt="" id="testImage">
<div id="testDiv">
<button type="button" id='testButton' class='first'>Hi</button>
</div>
I hope that what I am about to say makes more sense than I feel it does.
Your issue is that when you assign the click events, there is not currently an element that has a class of .second.
Also, your code is wrong. toggleClass accepts a few arguments, the first is a string of classes, the second is an optional parameter to check whether or not to toggle the classes on or off.
A way to accomplish what you want without changing a whole lot of code is event delegation, shown below.
$(function() {
$(document).on('click', '.btn-first,.btn-second', function() {
//here we are adding the click event on the document object, and telling it that we only want to delegate this event to an object that matches the classes of .btn-first or .btn-second.
//Note: to those saying "why not just do it on the .btn class an avoid having to do this", it is so he can see what delegation looks like. But you are correct, with this markup it would be better to simply add the click event on the .btn class.
$(this).toggleClass('btn-first btn-second');
});
});
.btn {
padding: 4px 8px;
border-radius: 3px;
border: 1px solid grey;
}
.btn-first {
background-color: green;
border-color: green;
}
.btn-second {
background-color: orange;
border-color: orange
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="img/images.jpeg" alt="" id="testImage">
<div id="testDiv">
<button type="button" id='testButton' class='btn btn-first'>Hi</button>
</div>
A combination of javascript, CSS and HTML to toggle the class of #testButton when any element of class "first" or "second" is clicked, including the test button itself. The posted code was changed to supply JQuery's .toggleClass method with a space separated list of class names. Click "run snippet" to test the effect.
$(document).ready(function(){
$('.first').click(function(){
$('#testButton').toggleClass('first second');
});
$('.second').click(function(){
$('#testButton').toggleClass('first second');
});
});
.first { border: thick outset green;}
.second { border: thick inset red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="first">This paragraph has first class</p>
<p class="second">This paragraph has second class</p>
<button type="button" id="testButton" class="first">this button starts out first class</div>
The script can then be simplified by combining multiple class names in a single selector, leaving just:
$(document).ready(function(){
$('.first, .second').click(function(){
$('#testButton').toggleClass('first second');
});
});
Make a neutral class that the buttons both share (.btn).
Then add one of the state classes to each button (.first or .second).
Delegate the click event to the neutral class only ($('.btn').on('click',...).
Then toggle both state classes on this ($(this).toggleClass('first second');)
The images change by CSS, each button has 2 images which alternate between display:none/block according to the button's state class.
There is an example with the images outside of buttons and another example that doesn't toggle classes around.
SNIPPET
$('.btn').on('click', function() {
$(this).toggleClass('first second');
});
/* OR */
$('.alt').on('click', function() {
$('.img').toggle();
});
.first > .one {
display: block;
}
.first > .two {
display: none;
}
.second > .one {
display: none;
}
.second > .two {
display: block;
}
.first + .one {
display: block;
}
.first + .one + .two {
display: none;
}
.second + .one {
display: none;
}
.second + .one + .two {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Use jQuery with CSS</p>
<button class='btn first'>
<img src='http://placehold.it/50x50/000/fff?text=1' class='one'>
<img src='http://placehold.it/50x50/fff/000?text=2' class='two'>
</button>
<button class='btn second'>
<img src='http://placehold.it/50x50/0e0/960?text=1' class='one'>
<img src='http://placehold.it/50x50/fff/000?text=2' class='two'>
</button>
<br/>
<br/>
<button class='btn first'>Toggle</button>
<img src='http://placehold.it/50x50/fc0/00f?text=1' class='one'>
<img src='http://placehold.it/50x50/00f/fc0?text=2' class='two'>
<button class='btn second'>Toggle</button>
<img src='http://placehold.it/50x50/fc0/00f?text=1' class='one'>
<img src='http://placehold.it/50x50/00f/fc0?text=2' class='two'>
<p>Or use only jQuery no CSS</p>
<img src='http://placehold.it/50x50/0e0/930?text=1' class='img'>
<img src='http://placehold.it/50x50/930/0e0?text=2' class='img' style='display:none'>
<button class='alt' style='display:block;'>Toggle</button>

stuck with onclick tried google couldn't find answer

i need help getting this to work, tried everything google had to offer.. but still stuck. what i need it to do is load the value of (div id="availablecredits") to (div id="beta") on click. can any body help me out?
onclick="javascript:document.getElementById('beta').value=(javascript:document.getElementById('availablecredits').value)"
i also tried onclick="javascript:document.getElementById('beta').value=('#availablecredits')"
The property value is common for input elements like <input>, <select>, <textarea> and <button>
I think what you want is to copy a content of a <div> element to another div. If it's the case, use innerHTML instead of value.
Here is a snippet, just click on the gray area.
#div-two {
min-height: 20px;
background: #CCC;
}
<div id="div-one">
Hello this is #div-one
</div>
<div id="div-two" onclick="document.getElementById('div-two').innerHTML=document.getElementById('div-one').innerHTML"></div>
SNIPPET #2
You've defined a third <div> which you use as trigger but you can't click it if it's not visible, because it's height is 0. Specify some text inside it, then it's visible and the JS part work. Take a look at the snippet.
#getCredits {
background: #CCC;
}
<div id="beta">0.00</div>
<div id="availablecredits">500</div>
<div id="getCredits" onclick="document.getElementById('beta').innerHTML=document.getElementById('availablecredits').innerHTML">Click here to get available credits</div>
SNIPPET #3 - jQuery
$('#getCredits').click(function() {
$("#beta").html($('#availablecredits').html());
});;
#getCredits {
background: #CCC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="beta">0.00</div>
<div id="availablecredits">500</div>
<div id="getCredits">Click here to get available credits</div>
Simple javascript function, change the ids in the function call to those of the elements in question.
<script>
function set_value( src,tgt ){
document.getElementById( tgt ).innerHTML=document.getElementById( src ).innerHTML;
}
</script>
<style>.p5{ display:block; padding:1rem; margin:1rem; border:1px solid black;}</style>
<div class='p5' id='src_div' onclick="set_value('src_div','tgt_div')">Weebles wobble but they don't fall down!</div>
<div class='p5' id='tgt_div'></div>
Or you can use a link to set the value
you should try to avoid writing inline event.try this:
<style>
#getCredits {
background: #CCC;
}
</style>
<div id="beta">0.00</div>
<div id="availablecredits">500</div>
<div id="getCredits">Click here to get available credits</div>
<script>
document.getElementById('getCredits').addEventListener("click",function(){
document.getElementById('beta').innerHTML=document.getElementById('availablecredits').innerHTML;
});
</script>
Why inline css and javascript are bad:http://robertnyman.com/2008/11/20/why-inline-css-and-javascript-code-is-such-a-bad-thing/
The .val() method is sometimes useful:
var input = $("#Input").val();

jquery sliding div are flickering

I am trying to make two divs sliding up and down on hover exactly like here: http://goo.gl/Ti1hjF (see the capable section). after hovering, the content of second div is doing up and down. I am going nuts trying to solve it. what am I doing wrong? here's the jquery :
$(".dormant").hover(function() {
var $detail = $(this).next(".detail")
if ($detail.is(":hidden")) {
$detail.slideToggle(1000);
} else {
$detail.slideUp('slow');
}
});
html:
<div class="col-md-4">
<div class="detail-container">
<div class="ivory dormant">
<div class="col-md-3 col-xs-2 center-block"><span class="bigicon doormat"></span> </div>
<h4>PARTNERSHIP + RELATIONSHIP</h4>
<p>We manage and deliver engagements and opportunities to further drive brand initiatives and further product and service objectives. We establish and implement targeted assessments which yield scalable results for our clients.</p>
<div class="col-md-4 col-xs-3 center-block pop-up"><i class="glyphicon glyphicon-plus-sign"></i> details</div>
</div>
<div class="red detail">
<div class="col-md-3 col-xs-2 center-block"><span class="bigicon doormat-white"></span></div>
<h4>PARTNERSHIP + RELATIONSHIP</h4>
<ul>
<li>Asset Management</li>
<li>Asset Development</li>
<li>Consumer Introduction</li>
<li>Relationship Management</li>
<li>Channel Strategies</li>
</ul>
</div>
</div>
</div>
and css:
.ivory{
background:#e7e6e6;
padding:2em;
margin-top:2em;
}
.red{
background:#8b0000;
color:white;
padding:2em;
}
#capabilities .red h4{
color:white;
}
.detail{
display:none;
position:absolute;
left:0;
top:0;
min-height:29em;
width:100%;
cursor:pointer;
}
.detail-container{
position:relative;
}
many thanks in advance. it is really driving me crazy.
jsFiddle
removing
else {
$detail.slideUp('slow');
}
should do the trick.
Here's an updated jsFiddle
I'm not sure whether you are looking for this or not.. I've changed the code like this.
$(".dormant").hover(function() {
var $detail = $(this).next(".detail")
if ($detail.is(":hidden")) {
$detail.slideToggle(1000);
}
});
$(".red.detail").click(function(){
$(this).slideUp(1000);
});
check this DEMO
Updated demo
After removing $detail.slideUp('slow');
You can use onmousemove and onmouseout html properties to hide/show required div.
This happened to me ones. I had an additional :hover on that div and the images didnt animate properly. Check if you have two :hovers on the div.
So, i think this still needs a bit of work, but to fix your immediately problem:
$(".dormant").hover(function(e) {
var $detail = $(this).next(".detail")
$detail.slideToggle(1000);
$detail.hover(function(e) {}, function(e) {
$detail.slideUp('slow');
});
}, function() {}
);
Basically adding an empty function for hover-out stops the odd behaviour and at least puts you on the right lines. I realise you're probably after an effect more akin to having the whole red div slide up, but this addresses your 'bouncy' problem.
jsFiddle

duplicate div then do a horizontal scroll

I'm trying to clone #main then put my ajax result there (hidden), after doing so I will make it scroll horizontally to the left hiding the current one then display the clone.
HTML:
<div class="container">
<div id="main">
<p>Click here to start</p>
</div>
</div>​
CSS:
#main{
width:460px;
min-height:200px;
background:#3F9FD9;
margin:0 auto;
}
.container {
position:relative;
}
​
Javascript:
$('#main').click(function(){
//clone.html(data)
var clone = $(this).clone().html('<p>Ajax loaded content</p>').css(
{position:'absolute',right:'0','margin-right':'-460px',top:0}
).attr('class','love').insertAfter($(this));
$(this).css({position:'relative'});
var width = $(window).width()-$(this).outerWidth()/2;
$('#main').animate({'left':'-'+width},4000);
});
but i'm stuck on the idea on how to make both #main animate to the left and position the second div at the center?
Fiddle
EDIT: Now i'm only stuck on how to animate the clone.
I sort of took a different approach to your question, is this kind of what you are looking for?
http://jsfiddle.net/3s7Fw/5/show
I thought, rather than do some animating ourselves, why not let jQuery's hide function do it for us? This could definitely be made to work better, but it communicates the thought.
JavaScript
$('.container').on('click', '.loaded-content', function(){
$this = $(this);
//clone.html(data)
var clone = $this.clone().html('<p>Ajax loaded content</p>').attr("id", '');
$this.after(clone);
$this.hide('slow');
});​
HTML
<div class="container">
<div id="main" class="loaded-content">
<p>Click here to start</p>
</div>
</div>​
CSS
#main, .loaded-content{
width:460px;
min-height:200px;
background:#3F9FD9;
margin:0 auto;
float: left;
}
.container {
position:relative;
width: 920px;
}
​If this is not the desired functionality, then you might be interested in a slider. There are a number of good slider plugins already out there that you can use. The difficult part would probably be adding a addNewSlide function to your chosen slider, assuming it didn't already have one.

Categories