click events in JavaScript - javascript

I'm building a list of images dynamically. What I want to happen is when a user clicks the close text (inside my DIV element) the code will delete that particular image (list element). The code below does that the FIRST time the DIV is selected. After that it seems to ignore my div event listener and jump straight into the jquery on click function.
function removeItem(){
var test = document.querySelector('li > div').addEventListener('click', function(){
$(document).on('click', 'li', function () {
var photoId = (this.id);
$("#"+photoId).remove();
});
});
How can I make it so it will ALWAYS run when the DIV is selected instead of just the first time?
I'm new to learning about JavaScript so any help is appreciated!

When the user clicks on the DIV, you're not removing anything, you're just adding a new click listener on all LIs that removes that LI. Then the user needs to click again to trigger the second handler. It should simply be:
$(document).on('click', 'li > div', function() {
$(this).parent().remove();
});
BTW, there's no point in writing
var photoId = (this.id);
$("#"+photoId).remove();
It's simply $(this).remove(). Why go searching for an ID when you already have a reference to the element itself?

Related

Mouse out event doesn't move back outside the button

I have a button and when you hover over it, it shows some text and 2 more buttons but when I move my mouse out of it, it still stays on the hover. How do I make my code work so that it works on mouse out?
This is my Javascript:
var option1Button_Mouseout = function() {
console.log('option1Button_Mouseout()');
$('laStyle-option1-button')[0].innerHTML = outputTag;
};
var attachOption1ButtonListeners = function() {
console.log($('laStyle-option1-button')[0]);
$('laStyle-option1-button')[0].addEventListener('mouseover', this.option1Button_Mouseover);
// When you mouse out of the button it brings it back to the original
$('laStyle-option1-button')[0].addEventListener('mouseout', this.option1Button_Mouseout);
};
window.onload = function() {
this.attachOption1ButtonListeners();
};
this is what it currently looks like:
https://media.giphy.com/media/9A6MoIdWBiZVFtcHyW/source.mp4
See when I hover over it it shows text and 2 buttons, when I mouse out it should go back to the picture of the hand.
Sind it is not clear what your methods are doing, consider this example:
HTML
<div id="myDiv">
<div id="myDiv1"/>
</div>
JavaScript
$('#myDiv').on("mouseover mouseenter ", function (e) {
$("#myDiv1").show();
});
$('#myDiv').on("mouseleave mouseout", function (e) {
$("#myDiv1").hide();
});
When entering the parent div the inner div will be shown. When leaving the parent div the inner div will be hidden. Also using .on as you are using jquery.
Here is the JSFiddle: https://jsfiddle.net/GR8sk/21/
Since you're already using jQuery I would use its Mouseenter and mouseleave events like so:
$("document").ready(function(){
$(".laStyle-option1-button img").mouseenter(function(){
$(this).attr('src','https://media.giphy.com/media/xUOwGdPZ0chBWiQ6Ri/giphy.gif');
});
$(".laStyle-option1-button img").mouseleave(function(){
$(this).attr('src','https://media.giphy.com/media/l4pTgiQB2e2dpuKs0/giphy.gif');
});
});
Couple things to note:
You did not add a '.' to the beginning of your jQuery reference to laStyle-option1-button (look at how the period goes before) because its a class attribute.
You are performing unnecessary event listener loading. While this can be helpful for binding to click events, I would just use the 'bind' method to bind functions to click events:
$( "#btnButton" ).bind( "click", myFunction);
You need to change either the 'src' attribute of the image, or just remove the button completely and replace with another one. The former is better performing.

Why is my jQuery not allowing me to toggle classes?

I have a series of custom Chevron elements that I'm going to use as buttons on my site. I've managed to set up the jQuery so that the clicked chevron/button is given a class="selected" which I then use to add custom styles. If I click any other chevron then the selected class is removed from the first chevron and added to the last chevron that was clicked. All of this works fine. I have another link that can be clicked to remove the class from all of the chevrons. What I'm trying to do now is to enable the .toggle(Class) function on jQuery so that I can also remove the class="selected" by clicking the same element twice.
My jQuery code:
$(function () {
$('#chevrons > ul > li > a').click( function(){
$('#chevrons .selected').removeClass('selected');
$('#show-all').removeAttr("style");
$(this).toggleClass('selected');
});
});
$(function () {
$('#show-all').click( function(){
$('#chevrons .selected').removeClass('selected');
$(this).css('color', '#FECF2A');
});
});
I've tried the toggle without the rows:
$('#chevrons .selected').removeClass('selected');
$('#show-all').removeAttr("style");
And it works fine. I assumed (perhaps incorrectly) that the jQuery would execute line-by-line and therefore the last thing to execute. But perhaps the first line above is removing the "selected" attribute from all of the chevrons and then the last line will only ever add the class.
What am I doing wrong here?
JSFiddle: http://jsfiddle.net/oqs4nycj/1/
Just exclude the clicked item from the class removal using not():
$('#chevrons .selected').not(this).removeClass('selected');
Applying this fix to your own JSFiddle (looks very cool by the way) you get this:
http://jsfiddle.net/qsnkqhp8/1/
JSFiddle:
http://jsfiddle.net/gopj0hyj/
Edit. I did not read the question carefully enough. Sorry. I have edited the code to deselect by clicking twice.
jQuery(function ($) {
// Variables are your friends - the $ preface tells us its a jQuery object
var $chevrons = $("#chevrons");
var $buttons = $chevrons.find('a');
var $show_all = $('#show_all');
// We bind a handler to the parent $chevrons element
// this is good for performance
// It will also bind the handler to elements dynamically added with ajax.
$chevrons.on('click', 'a', function(e){
var $old_selection = $buttons.filter('.selected');
var $clicked = $(this);
// Ensure that no button is selected
$buttons.removeClass('selected');
// Checks if button already was selected.
if ($clicked.get(0) !== $old_selection.get(0)) {
// select the clicked button
$clicked.addClass('selected');
}
$show_all.removeClass('active');
// prevents the browser from scrolling to top.
e.preventDefault();
});
$show_all.on('click', function(){
$buttons.removeClass('selected');
$(this).addClass('active');
});
});

How to append the div element in jquery if don't exist

I am adding the form my current list in a div box at the bottom of the table.
I am appending the div box when someone clicks on add button.
But when i click add button multiple times , then many div boxes are appended.
Is there any way that no matter how many times I click the button, only one instance gets append to div box.
This is my code
$var = $(this).parent().parent();
$var.append($('.jq_div')[0].outerHTML);
attach your listener using .one().
$("button").one('click', function(){
// Your code
});
Read more: http://api.jquery.com/one
This is under the assumption that you're using jQuery 1.7+
One simple solution would be having a boolean flag that you can toggle once your button is clicked. Additionally, there is actually a jQuery function that provides this exact functionality.
It's called one() -
Attach a handler to an event for the elements. The handler is executed
at most once per element.
So your code would look something like this -
$("#someTrigger").one('click', function(){
$var = $(this).parent().parent();
$var.append($('.jq_div')[0].outerHTML);
});
The boolean method is also very simple -
var wasClicked = false;
$("#someTrigger").on('click', function(){
if (wasClicked == false){
// append your form
wasClicked = true;
}
});
Reference -
one()

How do I trigger a mouseenter (or any mouse) event on list items within a div with a z-index?

Every time I click on the list items only the z-index layer gets the mouse event. CSS has no trouble detecting the mouse hovering over the list item but I need jquery to display an image after retrieving the background-image from the list item's css.
For your convenience, I recreated it at jsFiddle: http://jsfiddle.net/VaDb6/
I've also tried this:
jQuery hover problem due to z-index
But this just made everything else clickable in the back, which is exactly what
I don't want and the reason why I made the div with a z-index.
I've also tried giving each child a z-index but still no response from the list items.
I will greatly appreciate any suggestions or guidance. Thanks in advance!
This has nothing to do with the z-index, what is happening is that the events are binded when your page loads, and the freshly inserted divs don't have events attached to them. Here's how to fix it:
$('div.gallery_shots li').on('click', function () {
// take the ancestor's html
var html = $(this).parent().parent().next().html();
$('div#layerZ').html(html + '<div id="debug"></div>').show();
});
$('div#layerZ').on('click', function () {
$('div#debug').append('layerZ...');
});
$('div#layerZ')
.on("click", "li", function(e) {
e.stopPropagation();
alert('li clicked');
})
.on("mouseenter", "li", function(e) {
e.stopPropagation();
//$('div#layerZ div.gallery_pictures li.current').removeClass('current');
//$(this).addClass('current');
//var url = $(this).css('background-image');
//url = url.replace('url(', '').replace('-thumb', '').replace(')', '');
//$('div#layerZ div.large_gallery').html('<img src="'+url+'"></img>');
$('div#debug').append('mouseenter event success!!!<br />');
});
With $('div#layerZ').on("click", "li", function(e) {...} you're telling the parent to listen on clicks done specifically on li. Since #layerZ exists at load time there's no problem binding the event.​
http://jsfiddle.net/LbqUC/

Javascript/JQuery Execution order

I have multiple instances of a div ".gallery" and I want to pick up the id of the div the particular instance of .gallery is sitting in on click. This would then populate a variable that I can use to make the image only change in that div's gallery. Problem is that the page seems to try to do the image swap, then changes the variable, so the image doesn't change on the first click, and-worse-the first time you click on a different gallery it changes the image of the last gallery you interacted with. Currently there is a javascript alert that I have pop up every time you click a div that reports the div you clicked. I have the page in its current state here if you want to play around with it. www.ryanscasey.com/redesign
The straight javascript is as follows:
$(document).ready(function() {
var clickedDiv;
$('.gallery').click(function() {
clickedDiv = $(this).parent().parent().attr("id");
$('#' + clickedDiv + ' .thumbs img').click(function() {
$('#' + clickedDiv + ' .largeImage').html($(this).attr('alt'));
});
alert(clickedDiv);
});
});
I think this is what you want. It doesn't sound like you need to bind more than one click event. The way you had it, it would bind a click event any time a .gallery item was clicked. If this doesn't work, let me know, and we'll try to work from there.
$(document).ready(function() {
$('.gallery .thumbs img').click(function() {
var $this = $(this),
$gallery = $this.closest('.gallery'),
$large = $gallery.find('.largeImage');
$large.html($this.attr('alt'));
});
});
EDIT: I took a look at your site and I have adjusted my code. You want to bind the click event to the thumbnail not the entire gallery.

Categories