How can I make an element on hover? - javascript

All I'm trying to do is something like this mechanism:
Here is what I've tried so far:
$(document).ready(function(){
$('a').bind('mouseenter', function() {
var self = $(this);
this.iid = setInterval(function() {
var tag_name = self.text(),
top = self.position().top + self.outerHeight(true),
left = self.position().left;
self.append("<div class='tag_info'>Some explanations about"+tag_name+"</div>")
$(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
}, 525);
}).bind('mouseleave', function(){
this.iid && clearInterval(this.iid);
});
});
body{
padding: 20px;
}
a {
color: #3e6d8e !important;
background-color: #E1ECF4;
padding: 2px 5px;
}
.tag_info{
position: reletive;
width: 130px;
height: 30px;
display:none;
background-color: black;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a>tag1</a>
<a>tag2</a>
As you see, it will be repeated every time. How can I execute it once per hover? And why the position doesn't apply?
Also is what I'm doing a right algorithm for such thing?
Thank you.

I am not sure why you are using setInterval but I think this should work. I removed setInterval and everytime the mouseenter event occurs we can append <div class='tag_info'> and every time mouseleave event occurs we can remove the the appended div.
$(document).ready(function(){
$('#test').bind('mouseenter', function() {
var self = $(this);
var tag_name = self.text(),
top = self.position().top + self.outerHeight(true),
left = self.position().left;
self.append("<div class='tag_info'>Some explanations about"+tag_name+"</div>")
$(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
}).bind('mouseleave', function(){
$(this).children('.tag_info').remove();
});
});
body{
padding: 20px;
}
a {
color: #3e6d8e !important;
background-color: #E1ECF4;
padding: 2px 5px;
}
.tag_info{
position: reletive;
width: 130px;
height: 30px;
display:none;
background-color: black;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="test">tag1</a>

Like Dij said:
What you're doing:
setInterval - (repeats your function every 525ms)
What you want:
setTimeout - (executes your function once after 525ms delay)
Read more:
setInterval https://www.w3schools.com/jsref/met_win_setinterval.asp
setTimeout https://www.w3schools.com/jsref/met_win_settimeout.asp

Related

How to make divs names always be 1,2,3 jQuery

My issue is that when i append 2 divs white jQuery, there names are:
This is div 1
This is div 2
But when i remove the first div (This is div 1)
and append another div
it adds one more div whit name (This is div 2):
This is div 2
This is div 2
The reason is because the name of the div counts the total amout of divs... Is there any other way to number all divs so they will always be like this:
This is div 1
This is div 2
This is div 3
Even if i the divs are:
This is div 1
This is div 6
This is div 12
I want them always to be 1,2,3
jQuery code:
$('#add_item').click(function() {
//div count
var countDivs = $("div").length;
//append content
var removeBtn = ('<a class="removeBtn">x</a>')
var h2 = ('<h2>This is div '+countDivs+'</h2>')
var appendContent = ('<div>'+h2+removeBtn+'</div>')
$('#accordion').append(appendContent);
});
//remove button
$(document).on('click', '.removeBtn', function() {
$(this).parent('div').andSelf().remove();
return false;
});
JSFIDDLE
I think you'll have to edit contents of the divs each time a div is removed.
Let's say you have an element and you want to add divs to it.
You will add like you are right now and when you remove you edit all other divs.
The code would be something like this
$('#add_item').click(function() {
var countDivs = $("div").length;
var removeBtn = ('<a class="removeBtn">x</a>')
var h2 = ('<h2>This is div '+countDivs+'</h2>')
var appendContent = ('<div class="appDiv">'+h2+removeBtn+'</div>')
$('#accordion').append(appendContent);
});
$(document).on('click', '.removeBtn', function() {
$(this).parent('div').andSelf().remove();
$('.appDiv').each(function(index,el){
$(el).find('h2').text('This is div '+(index+1));
});
return false;
});
here is the Fiddle
Hope this helps :)
Write a function to renaming the divs and call it after append/remove.
function reArrange() {
$("#accordion > div").each(function(i) {
$(this).find("h2").text("This is div" + (i + 1))
});
}
Fiddle
When an item is removed, change the title of all the elements after it.
$('#add_item').click(function() {
var countDivs = $("#accordion div").length + 1;
var removeBtn = ('<a class="removeBtn">x</a>')
var h2 = ('<h2>This is div <span>' + countDivs + '</span></h2>')
var appendContent = ('<div>' + h2 + removeBtn + '</div>')
$('#accordion').append(appendContent);
});
$(document).on('click', '.removeBtn', function() {
var $div = $(this).parent();
$div.nextAll('div').find('span').html(function(i, html) {
return --html
});
$div.remove();
return false;
});
div {
position: relative;
}
#accordion {
margin-left: 60px;
padding: 10px;
background: #ddd;
}
#add_item {
position: absolute;
top: 20px;
left: 20px;
font-size: 20px;
padding: 5px 10px;
background: black;
color: white;
cursor: pointer;
}
.removeBtn {
font-size: 20px;
padding: 2px 10px 5px;
background: black;
color: white;
cursor: pointer;
position: absolute;
top: 0px;
font-family: verdana;
border-radius: 100%;
left: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="accordion">
</div>
<a id="add_item">+</a>
you should use a global variable like "count":
var count=1;
$('#add_item').click(function() {
//div count
//var countDivs = $("div").length;
var countDivs =count;
//append content
var removeBtn = ('<a class="removeBtn">x</a>')
var h2 = ('<h2>This is div '+countDivs+'</h2>')
var appendContent = ('<div>'+h2+removeBtn+'</div>')
$('#accordion').append(appendContent);
count++;
});
//remove button
$(document).on('click', '.removeBtn', function() {
$(this).parent('div').andSelf().remove();
return false;
});
The easiest update would be to trigger a recount (or other named-event) and, upon addition or removal of an element – by clicking either the #add_item or .removeBtn – call that function using the on() method to listen for that event.
In the below code we bind the event-listener to the #accordion element, as the closest ancestor present in the DOM on page load:
$('#add_item').click(function() {
var removeBtn = ('<a class="removeBtn">x</a>');
var h2 = ('<h2></h2>');
var appendContent = ('<div>'+h2+removeBtn+'</div>');
$('#accordion').append(appendContent).trigger('recount');
});
$(document).on('click', '.removeBtn', function() {
$(this).parent('div').andSelf().remove();
// triggering the 'recount' event from the
// #accordion:
$('#accordion').trigger('recount');
return false;
});
// listening for the 'recount' event:
$('#accordion').on('recount', function(){
// looking within the #accordion for
// the <h2> elements (which contain the
// text to update), and using the text()
// method's anonymous function along with
// its i argument (the index of the current
// <h2> in the collection):
$(this).find('h2').text(function(i){
// returning the text string concatenated
// with the index plus 1 (to get a 1-based
// count, rather than JavaScript's 0-based):
return 'This is div ' + (i + 1);
});
});
$('#add_item').click(function() {
var removeBtn = ('<a class="removeBtn">x</a>');
var h2 = ('<h2></h2>');
var appendContent = ('<div>' + h2 + removeBtn + '</div>');
$('#accordion').append(appendContent).trigger('recount');
});
$(document).on('click', '.removeBtn', function() {
$(this).parent('div').andSelf().remove();
$('#accordion').trigger('recount');
return false;
});
$('#accordion').on('recount', function() {
$(this).find('h2').text(function(i) {
return 'This is div ' + (i + 1);
});
});
div {
position: relative;
}
#accordion {
margin-left: 60px;
padding: 10px;
background: #ddd;
}
#add_item {
position: absolute;
top: 20px;
left: 20px;
font-size: 20px;
padding: 5px 10px;
background: black;
color: white;
cursor: pointer;
}
.removeBtn {
font-size: 20px;
padding: 2px 10px 5px;
background: black;
color: white;
cursor: pointer;
position: absolute;
top: 0px;
font-family: verdana;
border-radius: 100%;
left: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="accordion">
</div>
<a id="add_item">+</a>
References:
on().
text().
trigger().

change size of div function doesn't work

I have a function that alters the size of a div when I click on it. Now I have to write the onclick command in my html page, but I want it to stand in the extern .js file.
Now in html:
<div id="box1" class="kaesten" onclick="changeSize('box1')"> Title 1 </div>
What I want:
<div id="box1" class="kaesten" > Title 1 </div>
Tried something in jquery but it didn't work:
function changeSize(id) {
var elem = document.getElementById(id);
var currentAbsoluteElem = document.getElementById('dummy');
var text = elem.innerHTML;
currentAbsoluteElem.innerHTML = text;
currentAbsoluteElem.setAttribute('style', 'display:block');
/*Extra styling neeed to be done here*/
}
var elems = document.getElementsByClassName('kaesten');
for (var i = 0; i < elems.length; i++) {
elems[i].onclick = function() {
changeSize(this.id);
}
}
var absoluteCl = document.getElementsByClassName('absoluteclass');
absoluteCl[0].onclick = function() {
console.log(document.getElementsByClassName('absoluteclass'))
document.getElementsByClassName('absoluteclass')[0].setAttribute('style', 'display:none');
}
$(document).ready(function() {
$('.kaesten').click(function() {
changeSize($(this).attr('id'));
});
});
.kaesten {
width: 240px;
height: 300px;
background-color: darkgrey;
background-position: center;
background-repeat: no-repeat;
text-shadow: 0px 0px 3px #000;
border: 5px solid #F0F8ff;
vertical-align: top;
text-shadow: 3px 3px 4px #777;
float: left;
margin-left: 30px;
}
.absoluteclass {
position: absolute;
background-color: darkgrey;
width: 600px;
height: 600px;
left: calc(30%);
display: none;
}
<div id="box1" class="kaesten">title1</div>
<div id="box2" class="kaesten">title2</div>
<div id="box3" class="kaesten">title3</div>
<div id="box4" class="kaesten">title4</div>
<div id="dummy" class="absoluteclass"></div>
I know it works in the fiddle, but I don't know why it doesn't work on my homepage without writing the function in the div's.
I guess the problem is that you are trying to assign the onclick event handler before the DOM is actually rendered and ready. My suggestion is to wrap your "initialization code" inside a $(document).ready() method. As follows:
$(document).ready(function() {
// Apply the on click event handlers here, using jQuery or not
// For instance:
$('.kaesten').click(function() {
changeSize($(this).attr('id'));
});
});
if you want to pass the id from jquery to your function you should do it like this:
$(function(){
$(".kaesten").click(function(){
changeSize($(this).attr("id"));
});
});
you can use .css in jquery
$(function(){
$(".kaesten").click(function(){
$(this).css({'width' : '600px' , 'height' : '600px'});;
});
});

Make div all content below move down if div slides down

I'm trying to make this notification div that slides down if it is active. It slides down using this script:
<script type="text/javascript">
$(document).ready(function(){
$('#notice').slideDown(1000);
$('.exit').click(function(){
$("#notice").slideUp(400);
});
});
</script>
And the style is:
#notice {
background: #E0E0E0;
color: #FFF;
padding-left: 30px;
padding-top: 20px;
padding-bottom: 20px;
padding-right: 30px;
position: absolute;
z-index: 999999;
width: calc(100% - 60px);
top: 0;
font-weight: 200;
letter-spacing: 1px;
text-align: center;
display: none;
}
But how can I make this move everything else down as it slides down, even though the div below is at state 'position: fixed'. And slide everything else back up when it is removed using the .exit link.
Here you are one option to do it
Example here http://jsfiddle.net/jvarj4gk/2/
$('#notice').slideDown(1000);
var timer = setInterval(function () {
$('#fixed').css({
top: $('#notice').outerHeight()
});
if ($('#notice').outerHeight() == $('#fixed').css('top')) {
clearInterval(timer);
}
}, 10);
$('.exit').click(function () {
$("#notice").slideUp(400, function(){
$(this).remove();
});
$('#fixed').animate({
top: 0
}, 400);
});
Update
To move the #body you can do it like this
Example http://jsfiddle.net/jvarj4gk/5/
$('#notice').slideDown(1000);
var timer = setInterval(function () {
$('#fixed, #body').css({
top: $('#notice').outerHeight()
});
if ($('#notice').outerHeight() == $('#fixed').css('top')) {
clearInterval(timer);
}
}, 10);
$('.exit').click(function () {
$("#notice").slideUp(400, function(){
$(this).remove();
});
$('#fixed').animate({
top: 0
}, 400);
});
You can animate() the div below
var h = '+=' + $('#notice').height();
$('#fixedDivId').animate({
top: h;
},1000);
And almost the same stuff for slide up but h='-='+ $('#notice').height();
UPD
For your code it will look like this
$(document).ready(function(){
var h = $('#notice').height()+'px';
$('#notice').slideDown({duration:1000, queue:false});
$('#fixedDivId').animate({
top: h
},{duration:1000, queue:false});
$('.exit').click(function(){
$("#notice").slideUp(400);
});
});
Fiddle

Light box pop up form in jquery

Here is my code:
Please fill out my form.
<script>
var test = document.getElementById('test');
var win = null;
test.addEventListener('click', function(e) {
e.preventDefault();
e.stopPropagation();
win = window.open(test.href, null, 'height=823, width=680, toolbar=0, location=0, status=1, scrollbars=1, resizable=1');
return false;
});
window.addEventListener('click', function(e) {
if(win != null) {
win.close();
win = null;
}
});
</script>
This code works fine, but i need like to display as light box, for example please refer this site, http://fancybox.net/ ,, I am new to javascript, can anyone one help me to do this,
Any help would be appreciated, Thank you.
To start working with javascript, you would need a javascript library API. You must have heard about JQuery, this makes your work easier than regular Javascript codes. JQuery have lots of plugins especially for lightbox gallery that you are looking for. One useful lightbox plugin is Colorbox.
Start by importing the libraries to your header just like below. You also might need some css files for the colorbox themes.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
<script src="../jquery.colorbox.js"></script>
Then start using colorbox just like below
Please fill out my form.
$(document).ready(function(){
$("#test").click(function(){ //on clicking the link above
$(this).colorbox({ //this would capture the url from the href
width:'500px', //width of the colorbox
height:'auto', //height of the colorbox
initialWidth:'500px', //initial width upon loading
initialHeight:'auto', //initial height upon loading
speed:0, //animation speed
opacity:0.2, //background opacity
overlayClose: true, //close upon clicking anywhere
title:'Your Form Title', //your form title name
onComplete: function(){
//do something when the colorbox loaded completely
}
});
})
});
Take a look on this following example. This is custom light box without any plugin:
Updated Fiddle
jQuery:
var lightBox = $('#lightbox'),
lightBoxContent = $('#lb-content');
var positionLightbox = function() {
var veiwWidth = $(window).width(),
lbContentMargin = (veiwWidth / 2) - 148,
lbContent = $('#lb-content');
lbContent.css({
'left' : lbContentMargin,
'top' : $(window).scrollTop() + 50 + 'px'
});
};
$('#test').click(function(e) {
e.preventDefault();
lightBox.fadeIn(function() {
lightBoxContent.show();
});
positionLightbox();
});
$('#lb-close').click(function() {
lightBox.hide();
lightBoxContent.hide();
});
/*hide click outside*/
$(document).mouseup(function (e)
{
if (!lightBoxContent.is(e.target) // if the target of the click isn't the container...
&& lightBoxContent.has(e.target).length === 0) // ... nor a descendant of the container
{
lightBox.hide();
lightBoxContent.hide();
}
});
CSS:
body {color: #fff; font-family: arial; font-family: arial;}
#lightbox {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #000;
opacity: 0.8;
text-align: center;
display: none;
}
#lb-content {
color: #222;
height: 150px;
width: 260px;
border: 16px solid #222;
background-color: #fff;
position: relative;
text-align: center;
padding-top: 10px;
border-radius: 4px;
display: none;
}
#lb-close {
display: block;
height: 22px;
width: 25px;
background-color: red;
color: #fff;
position: absolute;
top: -25px;
right: -25px;
cursor: pointer;
text-align: center;
border-radius: 10px;
}
You can go for jQuery Plugin also:
http://lokeshdhakar.com/projects/lightbox2/
http://dimsemenov.com/plugins/magnific-popup/
http://www.jacklmoore.com/colorbox/

Doing a roll-in/roll-out slideshow in jQuery

I am trying to create a roll-in / roll-out slideshow in jQuery/JavaScript.
My problem is, that it needs to be repeated. And right now when it's starting over, the pictures doesnt come from the right side anymore :(
The reason for which I have created the slideLeft function, is that afterwards I need to create 2 functions, where the user can interrupt the slideshow manually pressing a left or right button.
This is what I've got:
<script class="jsbin" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<div style='background: #c4c4c4; border: 1px solid #7b7b7b; height: 220px; overflow: hidden; padding: 5px; position: absolute; width: 590px;'>
<div id='slider-image-1' style='left: 5px; background: red; height: 216px; padding: 2px; position: absolute; top: 5px; width: 586px;'></div>
<div id='slider-image-2' style='left: 600px; background: yellow; height: 216px; padding: 2px; position: absolute; top: 5px; width: 586px;'></div>
<div id='slider-image-3' style='left: 600px; background: green; height: 216px; padding: 2px; position: absolute; top: 5px; width: 586px;'></div>
<div id='slider-image-4' style='left: 600px; background: blue; height: 216px; padding: 2px; position: absolute; top: 5px; width: 586px;'></div>
</div>
<script type='text/javascript'>
$(document).ready(function() {
var amount = 0;
var nextamount = 1;
setInterval(function() {
amount++;
nextamount++;
if (nextamount === 5) nextamount = 1;
if (amount === 5) amount = 1;
slideLeft(amount, nextamount);
}, 2000);
});
function slideLeft(i, j) {
var $theItem = $('#slider-image-' + i);
$theItem.animate({
left: parseInt($theItem.css('left'), 10) == 5 ? -$theItem.outerWidth() : 5
}, 500);
var $theItem = $('#slider-image-' + j);
$theItem.animate({
left: parseInt($theItem.css('left'), 10) == 5 ? $theItem.outerWidth() + 10 : 5
}, 500);
};
</script>
You need to prepare element, which is going to roll in, to be on the right.
function slideLeft(i, j) {
var $theItem = $('#slider-image-' + i);
$theItem.animate({
left: parseInt($theItem.css('left'), 10) == 5 ? -$theItem.outerWidth() : 5
}, 500);
var $theItem = $('#slider-image-' + j);
$theItem.css('left', '600px'); // moves in item to the right before animation
$theItem.animate({
left: parseInt($theItem.css('left'), 10) == 5 ? $theItem.outerWidth() + 10 : 5
}, 500);
};
I think you've tried it with your parseInt, but it doesn't work, so you can get rid of it.
function slideLeft(i, j) {
var $outItem = $('#slider-image-' + i);
$outItem.animate({ left: -$outItem.outerWidth() }, 500);
var $inItem = $('#slider-image-' + j);
$inItem.css('left', '600px');
$inItem.animate({ left: 5 }, 500);
}
I have made something like this before, i dont know if this will help you, what i did was:
Add a copy of the first slide in the end of the collection of images/slides. Then, when you are showing the last "real" image and it will look like you are scrolling to the first image (but that is just a copy of the first image), and then when the animation is done you can position it with the default "left" css value. If you want it to scroll both ways, you can do the same with a copy of the last image/slide before the first image, but then you'll have to start the slider with a offset.
its a bit hard to explain, do you get the point? :)

Categories

Resources