Appended items should stay on hover and be away on leave - javascript

Basically when someone hovers over one certain item, more items should appear (which works) but when the mouse leaves that item, the items dissapear.
However I want the "hover area" to be the whole div containing the appended items so that the user can go through all the new IMGs
JavaScript
$("#mood").hover(
function() {
for (var i = 0; i < imgArr.length; i++) {
var img = $('<img />');
if (imgArr[i] != "") {
var img = $('<img />', {
src: '../img/mood/' + imgArr[i],
class: 'mood-item',
name: i
});
img.appendTo($('#mood-list'));
}
}
},
function() {
$("#mood-list img:gt(0)").remove()
}
);
HTML
<div class="form-group">
<label class="col-md-3 col-sm-4 control-label">Mood</label>
<div class="col-md-9 col-sm-8" id="mood-list">
<img src="...." id="mood"/>
</div>
</div>

You will have to use two different events since your condition is #mood-list div should be populated when #mood is hovered yet should be emptied when #mood-list no longer has the cursor
$("#mood").hover(
function() {
for (var i = 0; i < imgArr.length; i++) {
var img = $('<img />');
if (imgArr[i] != "") {
var img = $('<img />', {
src: '../img/mood/' + imgArr[i],
class: 'mood-item',
name: i
});
img.appendTo($('#mood-list'));
}
}
}
);
$('#mood-list').mouseleave(
function() {
$("#mood-list img:gt(0)").remove()
});
Update
if I hover 2 times over the first element (which causes the others to
appear), every item appears twice
In your case, you can check for siblings like
$("#mood").hover(
function() {
if(!$(this).siblings().length){
for (var i = 0; i < imgArr.length; i++) {
var img = $('<img />');
if (imgArr[i] != "") {
var img = $('<img />', {
src: '../img/mood/' + imgArr[i],
class: 'mood-item',
name: i
});
img.appendTo($('#mood-list'));
}
}
}
}
);
Do you know what I have to change if I want to put this img into a
?
Replace
img.appendTo($('#mood-list'));
with
var anchor = $('<a></a>');
img.appendTo(anchor);
anchor.appendTo($('#mood-list'));

Related

How to select images in array to fade in and out

var n=0;
var images=["FullSizeRender (1).jpg","IMG_1875.JPG","IMG_4665.JPG","IMG_5213.JPG"];
$(document).ready(function() {
// Change image
$("#himg").click(function(){
n++;
if(n==images.length){
n=0;
};
document.getElementById("himg").src=images[n];
$("#himg").find('img[src="' + images[n] + '"]').fadeOut();
$("#himg").find('img[src="' + images[n+1] + '"]').hide().fadeIn();
});
<div class="col-xs-2">
<div id="handbags">
<h4>Handbags</h4>
<img id="himg" src="FullSizeRender (1).jpg" />
</div>
</div>
I have made an array where images change on click, but I am trying to make the images fade on click instead of sharply changing. I've tried selecting the images by source using the index from the array, but it's not working.
Try this:
$(document).ready(function() {
var n = 0;
var images = ["FullSizeRender(1).jpg","IMG_1875.JPG","IMG_4665.JPG","IMG_5213.JPG"];
var image = $('#himg');
image.on('click', function() {
var newN = n+1;
if (newN >= images.length) { newN = 0 };
image.attr('src', images[n]);
image.fadeOut(300, function () {
image.attr('src', images[newN]);
image.fadeIn();
n = newN;
});
});
});

clicking on an image from a gallery and showing multiple images in the same page

I have an image gallery and I want to click on each image to show 4 related image to it. What is the best way to do this without creating a whole new page for each image to show its related images?
I am using this for image gallery:
http://codepen.io/dimsemenov/pen/ZYbPJM
For now I have used Adobe InDesign to show the four images in one png file (due to space limits) but of course there are more aesthetic and smart ways. Please suggest solutions.
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Imgur Results</title>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/photoswipe.min.css'>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/default-skin/default-skin.min.css'>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h2>Banana:</h2>
<div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery">
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="imgur/banana/banana1.png" itemprop="contentUrl" data-size="900x900">
<img src="imgur/banana/3NlNsLB.jpg" itemprop="thumbnail" alt="Image description" />
</a>
</figure>
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="imgur/banana/banana2.tif" itemprop="contentUrl" data-size="900x900">
<img src="imgur/banana/6gqpgDV.jpg" itemprop="thumbnail" alt="Image description" />
</a>
</figure>
https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/photoswipe.min.js'>
<script src="js/index.js"></script>
Here's the js:
var initPhotoSwipeFromDOM = function(gallerySelector) {
// parse slide data (url, title, size ...) from DOM elements
// (children of gallerySelector)
var parseThumbnailElements = function(el) {
var thumbElements = el.childNodes,
numNodes = thumbElements.length,
items = [],
figureEl,
linkEl,
size,
item;
for(var i = 0; i < numNodes; i++) {
figureEl = thumbElements[i]; // <figure> element
// include only element nodes
if(figureEl.nodeType !== 1) {
continue;
}
linkEl = figureEl.children[0]; // <a> element
size = linkEl.getAttribute('data-size').split('x');
// create slide object
item = {
src: linkEl.getAttribute('href'),
w: parseInt(size[0], 10),
h: parseInt(size[1], 10)
};
if(figureEl.children.length > 1) {
// <figcaption> content
item.title = figureEl.children[1].innerHTML;
}
if(linkEl.children.length > 0) {
// <img> thumbnail element, retrieving thumbnail url
item.msrc = linkEl.children[0].getAttribute('src');
}
item.el = figureEl; // save link to element for getThumbBoundsFn
items.push(item);
}
return items;
};
// find nearest parent element
var closest = function closest(el, fn) {
return el && ( fn(el) ? el : closest(el.parentNode, fn) );
};
// triggers when user clicks on thumbnail
var onThumbnailsClick = function(e) {
e = e || window.event;
e.preventDefault ? e.preventDefault() : e.returnValue = false;
var eTarget = e.target || e.srcElement;
// find root element of slide
var clickedListItem = closest(eTarget, function(el) {
return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
});
if(!clickedListItem) {
return;
}
// find index of clicked item by looping through all child nodes
// alternatively, you may define index via data- attribute
var clickedGallery = clickedListItem.parentNode,
childNodes = clickedListItem.parentNode.childNodes,
numChildNodes = childNodes.length,
nodeIndex = 0,
index;
for (var i = 0; i < numChildNodes; i++) {
if(childNodes[i].nodeType !== 1) {
continue;
}
if(childNodes[i] === clickedListItem) {
index = nodeIndex;
break;
}
nodeIndex++;
}
if(index >= 0) {
// open PhotoSwipe if valid index found
openPhotoSwipe( index, clickedGallery );
}
return false;
};
// parse picture index and gallery index from URL (#&pid=1&gid=2)
var photoswipeParseHash = function() {
var hash = window.location.hash.substring(1),
params = {};
if(hash.length < 5) {
return params;
}
var vars = hash.split('&');
for (var i = 0; i < vars.length; i++) {
if(!vars[i]) {
continue;
}
var pair = vars[i].split('=');
if(pair.length < 2) {
continue;
}
params[pair[0]] = pair[1];
}
if(params.gid) {
params.gid = parseInt(params.gid, 10);
}
return params;
};
var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
var pswpElement = document.querySelectorAll('.pswp')[0],
gallery,
options,
items;
items = parseThumbnailElements(galleryElement);
// define options (if needed)
options = {
// define gallery index (for URL)
galleryUID: galleryElement.getAttribute('data-pswp-uid'),
getThumbBoundsFn: function(index) {
// See Options -> getThumbBoundsFn section of documentation for more info
var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
rect = thumbnail.getBoundingClientRect();
return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
}
};
// PhotoSwipe opened from URL
if(fromURL) {
if(options.galleryPIDs) {
// parse real index when custom PIDs are used
// http://photoswipe.com/documentation/faq.html#custom-pid-in-url
for(var j = 0; j < items.length; j++) {
if(items[j].pid == index) {
options.index = j;
break;
}
}
} else {
// in URL indexes start from 1
options.index = parseInt(index, 10) - 1;
}
} else {
options.index = parseInt(index, 10);
}
// exit if index not found
if( isNaN(options.index) ) {
return;
}
if(disableAnimation) {
options.showAnimationDuration = 0;
}
// Pass data to PhotoSwipe and initialize it
gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
};
// loop through all gallery elements and bind events
var galleryElements = document.querySelectorAll( gallerySelector );
for(var i = 0, l = galleryElements.length; i < l; i++) {
galleryElements[i].setAttribute('data-pswp-uid', i+1);
galleryElements[i].onclick = onThumbnailsClick;
}
// Parse URL and open gallery if it contains #&pid=3&gid=1
var hashData = photoswipeParseHash();
if(hashData.pid && hashData.gid) {
openPhotoSwipe( hashData.pid , galleryElements[ hashData.gid - 1 ], true, true );
}
};
// execute above function
initPhotoSwipeFromDOM('.my-gallery');
here's the CSS:
.my-gallery {
width: 100%;
float: left;
}
.my-gallery img {
width: 200px;
height: 200px;
display: block;
}
.my-gallery figure {
display: block;
float: left;
margin: 0px 15px 20px 0;
border: 3px solid #000;
}
.my-gallery figcaption {
display: none;
}
Also is there an easier way to have this image gallery without using this library above?
Basically I would like to show something like this when you click on an image:
^ the above is made with adobe illustrator though and would be nice to make it with html/css.
This is how the gallery itself shows:
You can achieve this by using Fancybox.
See this Fiddle.
In this example, clicking on the visible image triggers a click event that opens an hidden gallery using Fancybox.
HTML
<!-- Your visible image(s) -->
<a class="fancyboxLauncher" href="http://fancyapps.com/fancybox/demo/1_b.jpg" title="one"><img src="http://fancyapps.com/fancybox/demo/1_s.jpg" alt="" /></a>
<!-- Your hidden gallery -->
<div style="display: none;">
<a class="fancybox" href="http://farm4.staticflickr.com/3712/9032543579_1217e6566b_b.jpg" title="one"></a>
<a class="fancybox" href="http://farm4.staticflickr.com/3818/9036037912_83576fe5ab_b.jpg" title="two"></a>
JS
// Trigger event
$(".fancyboxLauncher").on("click", function () {
$(".fancybox").eq(0).trigger("click");
return false;
});
// Init Fancybox
$(".fancybox")
.attr('rel', 'gallery')
.fancybox({
padding: 0
});
You can still use the 4-in-1 image of course, just use 1 image instead of 4. Regardless, you have a lot of options with it.

jQuery $(document).on( eventName, selector, function(){} ) not working [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
I had a click function which functioned when I had this elements hidden on page load, and then showed them later. Now I am appending those elements on click after the page has loaded, and the function of course doesn't work. I thought I would fixed the problem with load() function but it still doesn't work. This is the html I append on click:
$('#magazine-detail')[0].innerHTML = '<section id="magazine-detail" class="magazine-detail"><div class="large-6 medium-6 small-12 columns"><div class="magazine-hero"><img id="image" src="/imagecache/cover/' + magazineImage + '" alt="' + name + '" /><div class="magazine-preview-nav"><div class="right-arrow" id="forward"><img src="/img/right-arrow-black.svg" /><p>Neste utgivelse</p></div><div class="left-arrow" id="back"><img src="/img/left-arrow-black.svg" /><p>Forrige utgivelse</p></div></div></div></div><div class="large-6 medium-6 small-12 columns"><div class="row"><div class="small-6 columns magazine-title"><h1 id="name"></h1></div></div><p id="summary"></p><img id="issueImage" src="" alt="" /><p></p><button class="button primary expand">Kjøp abonnement - 1 måned gratis</button><button class="button secondary expand">Bla igjennom arkivet</button></div></section>';
There I create #forward and #back elements, for which I have functions on click in my script:
$(document).ready(function () {
var imagesIndex = 0;
nextImage = 0;
loadedImages = new Array();
function preload() {
for (i = 0; i < 2; i++) {
if (nextImage < images.length) {
var img = new Image();
img.src = '/imagecache/cover/' + images[nextImage];
loadedImages[nextImage] = img;
++nextImage;
}
}
}
$('#forward').load('click', function() {
imagesIndex++;
preload();
if (imagesIndex > (loadedImages.length - 1)) {
imagesIndex = loadedImages.length - 1;
}
$('#image').attr({"src" : loadedImages[imagesIndex].src, "alt" : name});
});
$('#back').load('click', function() {
imagesIndex--;
if (imagesIndex < 0) {
imagesIndex = 0;
}
$('#image').attr({"src" : loadedImages[imagesIndex].src, "alt" : name});
});
});
I have tried with:
$(document).on('click','#forward', function() {
console.log('entered');
imagesIndex++;
preload();
if (imagesIndex > (loadedImages.length - 1)) {
imagesIndex = loadedImages.length - 1;
}
$('#image').attr({"src" : loadedImages[imagesIndex].src, "alt" : name});
});
$(document).on('click','#forward', function() {
imagesIndex--;
if (imagesIndex < 0) {
imagesIndex = 0;
}
$('#image').attr({"src" : loadedImages[imagesIndex].src, "alt" : name});
});
But nothing gets logged when I click on the element.
$("#existingParent").on("click", ".child", function() {
// do stuff
});
write like this
$(document).on('click','#forward', function() {

Jquery tab is not working

I have one problem with click function. I have created this demo from jsfiddle.net.
In this demo you can see there are smile buttons. When you click those buttons then a tab will be opening on that time. If you click the red button from tab area then the tab is not working there are something went wrong.
Anyone can help me here what is the problem and what is the solution?
The tab is normalize like this working demo
var response = '<div class="icon_b">
<div class="clickficon"></div>
<div class="emicon-menu MaterialTabs">
<ul>
<li class="tab active"> TAB1</li>
<li class="tab"> TAB2</li>
<li class="tab"> TAB3<span></span></li>
</ul>
<div class="panels">
<div id="starks-panel1" class="panel pactive"> a </div>
<div id="lannisters-panel1" class="panel"> b </div>
<div id="targaryens-panel1" class="panel"> c </div>
</div>
</div>
</div>';
$(document).ready(function () {
function showProfileTooltip(e, id) {
//send id & get info from get_profile.php
$.ajax({
url: '/echo/html/',
data: {
html: response,
delay: 0
},
method: 'post',
success: function (returnHtml) {
e.find('.user-container').html(returnHtml).promise().done(function () {
$('.emoticon').addClass('eactive');
});
}
});
}
$('body').on('click', '.emoticon', function(e) {
var id = $(this).find('.emoticon_click').attr('data-id');
showProfileTooltip($(this), id);
});
$(this).on( "click", function() {
$(this).find('.user-container').html("");
});
var componentHandler = function() {
'use strict';
var registeredComponents_ = [];
var createdComponents_ = [];
function findRegisteredClass_(name, opt_replace) {
for (var i = 0; i < registeredComponents_.length; i++) {
if (registeredComponents_[i].className === name) {
if (opt_replace !== undefined) {
registeredComponents_[i] = opt_replace;
}
return registeredComponents_[i];
}
}
return false;
}
function upgradeDomInternal(jsClass, cssClass) {
if (cssClass === undefined) {
var registeredClass = findRegisteredClass_(jsClass);
if (registeredClass) {
cssClass = registeredClass.cssClass;
}
}
var elements = document.querySelectorAll('.' + cssClass);
for (var n = 0; n < elements.length; n++) {
upgradeElementInternal(elements[n], jsClass);
}
}
function upgradeElementInternal(element, jsClass) {
if (element.getAttribute('data-upgraded') === null) {
element.setAttribute('data-upgraded', '');
var registeredClass = findRegisteredClass_(jsClass);
if (registeredClass) {
createdComponents_.push(new registeredClass.classConstructor(element));
} else {
createdComponents_.push(new window[jsClass](element));
}
}
}
function registerInternal(config) {
var newConfig = {
'classConstructor': config.constructor,
'className': config.classAsString,
'cssClass': config.cssClass
};
var found = findRegisteredClass_(config.classAsString, newConfig);
if (!found) {
registeredComponents_.push(newConfig);
}
upgradeDomInternal(config.classAsString);
}
return {
upgradeDom: upgradeDomInternal,
upgradeElement: upgradeElementInternal,
register: registerInternal
};
}();
function MaterialTabs(element) {
'use strict';
this.element_ = element;
this.init();
}
MaterialTabs.prototype.Constant_ = {
MEANING_OF_LIFE: '42',
SPECIAL_WORD: 'HTML5',
ACTIVE_CLASS: 'pactive'
};
MaterialTabs.prototype.CssClasses_ = {
SHOW: 'materialShow',
HIDE: 'materialHidden'
};
MaterialTabs.prototype.initTabs_ = function(e) {
'use strict';
this.tabs_ = this.element_.querySelectorAll('.tab');
this.panels_ = this.element_.querySelectorAll('.panel');
for (var i=0; i < this.tabs_.length; i++) {
new MaterialTab(this.tabs_[i], this);
}
};
MaterialTabs.prototype.resetTabState_ = function() {
for (var k=0; k < this.tabs_.length; k++) {
this.tabs_[k].classList.remove('pactive');
}
};
MaterialTabs.prototype.resetPanelState_ = function() {
for (var j=0; j < this.panels_.length; j++) {
this.panels_[j].classList.remove('pactive');
}
};
function MaterialTab (tab, ctx) {
if (tab) {
var link = tab.querySelector('a');
link.addEventListener('click', function(e){
e.preventDefault();
var href = link.href.split('#')[1];
var panel = document.querySelector('#' + href);
ctx.resetTabState_();
ctx.resetPanelState_();
tab.classList.add('pactive');
panel.classList.add('pactive');
});
}
};
MaterialTabs.prototype.init = function() {
if (this.element_) {
this.initTabs_();
}
}
window.addEventListener('load', function() {
componentHandler.register({
constructor: MaterialTabs,
classAsString: 'MaterialTabs',
cssClass: 'MaterialTabs'
});
});
});
There is updated and working version.
What we have to do, is to move the target on the same level as the icon is (almost like tab and content). Instead of this:
<div class="emoticon">
<div class="emoticon_click" data-id="1">
<img src="http://megaicons.net/static/img/icons_sizes/8/178/512/emoticons-wink-icon.png" width="30px" height="30px">
<div class="user-container" data-upgraded></div>
</div>
</div>
We need this
<div class="emoticon">
<div class="emoticon_click" data-id="1">
<img src="http://megaicons.net/static/img/icons_sizes/8/178/512/emoticons-wink-icon.png" width="30px" height="30px">
// not a child
<!--<div class="user-container" data-upgraded></div>-->
</div>
// but sibling
<div class="user-container" data-upgraded></div>
</div>
And if this is new HTML configuration, we can change the handlers
to target click on div "emoticon_click"
change the content of the sibling (not child) div "user-container"
The old code to be replaced
$('body').on('click', '.emoticon', function(e) {
var id = $(this).find('.emoticon_click').attr('data-id');
showProfileTooltip($(this), id);
});
$(this).on( "click", function() {
$(this).find('.user-container').html("");
});
will now be replaced with this:
//$('body').on('click', '.emoticon', function(e) {
$('body').on('click', '.emoticon_click', function(e) {
// clear all user container at the begining of this click event
$('body').find('.user-container').html("");
// find id
var id = $(this).attr('data-id');
// find the parent, which also contains sibling
// user-container
var parent = $(this).parent()
// let the target be initiated
showProfileTooltip($(parent), id);
});
$(this).on( "click", function() {
//$(this).find('.user-container').html("");
});
Check it in action here
NOTE: the really interesting note was in this Answer by pinturic
If we want to extend the first and complete answer with a feature:
close all tabs if clicked outside of the area of tabs or icons
we just have to
add some event e.g. to body
and do check if the click was not on ".emoticon" class elements
There is a working example, containing this hook:
$('body').on( "click", function(e) {
// if clicked in the EMOTICON world...
var isParentEmotion = $(e.toElement).parents(".emoticon").length > 0 ;
if(isParentEmotion){
return; // get out
}
// else hide them
$('body').find('.user-container').html("");
});
I have been debugging your code and this is the result:
you are adding the "tab" under ; any time you click within that div this code is intercepting it:
$('body').on('click', '.emoticon', function(e) {
var id = $(this).find('.emoticon_click').attr('data-id');
showProfileTooltip($(this), id);
});
and thus the "tab" are built again from scratch.

How to show all div's inside images titles onmouseover?

I have a div containing images and I want to show all of the inside image's titles onmouseover.
So, I have something like this :
<div id=MyDiv onmouseover="highlight(this);">
And my javascript :
function highlight(element) {
for (var i = 0; i < element.children.length; i++) {
if (element.children[i].tagName == "IMG")
element.children[i].title.show();
}
}
But all i get is a message - Object "X" has no method show.
You are using plain JavaScript. title is a string, and as the message says, it has no method show.
If what you want to do is alert all the titles in a pop-up, you can do this:
function highlight(element) {
for (var i = 0; i < element.children.length; i++) {
if (element.children[i].tagName == "IMG")
alert(element.children[i].title);
}
}
If, on the other hand you want to show them on your page you need something like this:
function highlight(element) {
var outputelement = document.getElementById("idofsomeelementyouhaveonyourpage");
for (var i = 0; i < element.children.length; i++) {
if (element.children[i].tagName == "IMG")
outputelement.innerHTML += element.children[i].title;
}
}
Of course, with the second method, you'd need an onmouseout handler that hides the titles as well.
Here is an example using jQuery:
HTML:
<div id="MyDiv">
<img src="http://chandra.harvard.edu/photo/2012/m101/m101_xray_thm100.jpg" title="img1" />
<img src="http://passport-cdn.mobilenations.com/avatars/000/004/072/100x100_4072871.jpg?r=1" title="img2" />
</div>
jQuery:
$("#MyDiv").mouseenter(function () {
$mydiv = $(this);
$.each($('img', $mydiv), function () {
var pos = $(this).position();
$('<div>', {
class: 'imgtitle'
}).css({
position: 'absolute',
color: 'red',
top: pos.top + 5,
left: pos.left + 5
})
.html($(this).attr('title'))
.insertAfter($(this));
});
}).mouseleave(function () {
$('.imgtitle').remove();
});
Here's a jsfiddle showing it in action: http://jsfiddle.net/obryckim/k5hcJ/

Categories