Generic Javascript Code - javascript

I wrote a code for a hover functionality. Now, I am asking myself how to make this code generic in order to show different divs when hovering over a different link. The JavaScript code is as follows:
<script>
$(function() {
var moveLeft = 20;
var moveDown = 10;
$('a#trigger').hover(function(e) {
$('div#purpose').show();
}, function() {
$('div#purpose').hide();
});
$('a#trigger').mousemove(function(e) {
$("div#purpose").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});
});
</script>
The div I call is as follows:
<!-- Purpose: Hover Popup -->
<div class= id="purpose">
<h3>Purpose</h3>
<p>
Test
</p>
</div>
Furthermore, I added some CSS style
<!-- Style for Hovering -->
<style type="text/css">
div#purpose {
display: none;
position: absolute;
width: 280px;
padding: 10px;
background: #eeeeee;
color: #000000;
border: 1px solid #1a1a1a;
font-size: 90%;
}
</style>
Could anybody tell me how to make this code generic in order to add further divs which are called from another link?

Create a javascript function and pass in the variables (e.g. link and div)
function foo($link, $div){
var moveLeft = 20;
var moveDown = 10;
$link.hover(function(e) {
$div.show();
}, function() {
$div.hide();
});
$link.mousemove(function(e) {
$div.css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});
}
For your existing behaviour call the following for example:
foo($('a#trigger'), $("div#purpose"));
This will actually be slightly better for performance as you'll be using the same jQuery reference each time. However depending on how you're actually planning on using this, having a seperate function call each time might not be the best way.
For example if you wish to use this on dynamic data it wouldn't be sensible to make static calls to a function each time.

Make use of custom data-* attributes in your HTML, and use classes to target a generalized group of elements, ex:
<a class="trigger" data-target="purpose" />
And the JS
$(".trigger").hover(function(e) {
var elemToShow = $(this).data("target");
$("#" + elemToShow).show();
}, function() {
var elemToShow = $(this).data("target");
$("#" + elemToShow).show();
}).mousemove(function(e) {
var elemToShow = $(this).data("target");
$("#" + elemToShow).css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});

You could build your trigger elements in a way that they hold the information about what element to show:
<a class="trigger" data-show="purpose">...</a>
Then you initialize them all at once like this:
$(function() {
$('.trigger').hover(function() {
var elementId = $(this).data('show');
$('#'+elementId).show();
}, function() {
var elementId = $(this).data('show');
$('#'+elementId).hide();
);
});

You don't need any JavaScript or jQuery at all for this--you can simply use CSS with the :hover pseudo-class.
.menu {
background-color: #eee;
}
.menuItem {
display: inline-block;
}
.menu .trigger + .purpose {
display: none;
position: absolute;
background-color: #eee;
}
.menu .trigger:hover + .purpose, .menu .trigger + .purpose:hover {
display: block;
}
<div class="menu">
<div class="menuItem">
Trigger 1
<div class="purpose">
<h3>Purpose 1</h3>
<p>
Test 1
</p>
</div>
</div>
<div class="menuItem">
Trigger 2
<div class="purpose">
<h3>Purpose 2</h3>
<p>
Test 2
</p>
</div>
</div>
<div class="menuItem">
Trigger 3
<div class="purpose">
<h3>Purpose 3</h3>
<p>
Test 3
</p>
</div>
</div>
<div class="menuItem">
Trigger 4
<div class="purpose">
<h3>Purpose 4</h3>
<p>
Test 4
</p>
</div>
</div>
</div>

Related

swap div's position from top div's

I am trying to swap a div's position from top on and when I click another div then top div can be swap.
HTML
<div class="wrap top">
<input type="text" value="div1" class="textbox " />
</div>
<div class="wrap">
<input type="text" value="div2" class="textbox " />
</div>
<div class="wrap">
<input type="text" value="div3" class="textbox " />
</div>
jQuery
(function ($) {
$(".wrap").on("click", function () {
if ($(this).index() == 0) {
} else {
$(this).insertBefore($(this).prev());
}
});
}(jQuery));
The fact is I don't want to remove the div which I click instead want to swap the positions around.
How Can I do this using jQuery itself?
I would suggest using css to position the top div and just swap the class as follows:
(function ($) {
$(".wrap").on("click", function () {
if ($(this).index() == 0) {
} else {
$(".wrap").removeClass("top");
$(this).addClass("top");
}
});
}(jQuery));
this will swap whatever you click with the first element.
$(".wrap").on("click", function () {
var $this = $(this);
if ($this.index() == 0) {
} else {
var first = $this.siblings('.wrap').first();
first.insertBefore($this);
$this.prependTo($this.parent());
}
});
if you just want to move the clicked element to the top, you can simply do
$this.prependTo($this.parent());
To swap the two DOM elements using jQuery, you could use something like this: -
(function($) {
$(".wrap").on("click", function(event) {
var index = $(event.target).index();
var first = $(".wrap").first();
if (index > 0) {
$(first).swapWith(this);
}
});
}(jQuery));
jQuery.fn.swapWith = function(to) {
return this.each(function() {
var copy_to = $(to).clone(true);
var copy_from = $(this).clone(true);
$(to).replaceWith(copy_from);
$(this).replaceWith(copy_to);
});
};
.wrap {
height: 100px;
width: 200px;
margin: 10px 10px 10px 10px;
background-color: #2d8cd0;
}
h2 {
color: white;
text-align: center;
padding-top: 20px;
pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="wrap">
<h2>1</h2>
</div>
<div class="wrap">
<h2>2</h2>
</div>
<div class="wrap">
<h2>3</h2>
</div>
<div class="wrap">
<h2>4</h2>
</div>

How to use the jQuery Selector in this web application?

I am trying to work out to select a delete icon in my own web application. delectIcon
HTML
<main>
<div class="container">
<div class="tabs">
<p><span class="active">Newest</span></p><a href=""><p>
<span>Oldest</span></p></a><p><span>Add</span></p>
</div>
<div class="content">
<ul>
<li>
<span class="itemLeft">Answer emails</span>
<span class="itemMiddle">12-31-2016</span>
<span class="itemRight">1</span>
<b class="deleteIcon"> X </b>
</li>
<li>
<span class="itemLeft">Prep for Monday's class</span>
<span class="itemMiddle">12-31-2016</span>
<span class="itemRight">5</span>
<b class="deleteIcon"> X </b>
</li>
</ul>
</div>
</div>
</main>
JavaScript
$(".deleteIcon").on("click", function () {
alert("Oh, clicked!");
return false;
});
I failed to do so by writing it myself. So I used Chrome Web Developer Tool to find the CSS path. I tried to use the XPath($"[/html/body/main/div/div[2]/ul/li[ 1 ]/b]") and CSS Path ($"(pathbody > main > div > div.content > ul > li:nth-child(1) > b)"). Neither of them worked.
I tried to mark it with an ID and made only one "li" exists. The CSS selector worked all right. But when I clicked the deleteIcon$"(#deleteIcon)", nothing happened.
#deleteIcon{
float:right;
font-weight: bold;
padding: 0 3px 0 3px;
border-radius: 5px;
background: #ccc;
cursor: pointer;
margin-left: 5px;
font-size: 1.3em;
text-align: center;
}
I also tried to select my title. I found the following worked out.
$(".container h1").on("click", function () {
alert("Oh, no!");
return false;
});
I do not what to do now. Can anyone help me out here?
Thank you! I would be really appreciate if you can answer my question.
Adding more details:
I did actually add the deleteIcon into the HTML by JavaScript. I do not know whether this can have an effect on my selector.
Actual HTML
<main>
<div class="container">
<div class="tabs">
<p><span class="active">Newest</span></p><a href=""><p>
<span>Oldest</span></p></a><p><span>Add</span></p>
</div>
<div class="content">
</div>
</div>
</main>
JavaScript (The important part listed below)
function Item(name,dueDate,type){
this.name=name;//1
this.dueDate=dueDate;//input2
this.type=type;//3
};
$(".tabs a span").toArray().forEach(function (element) {
var $element = $(element);
// create a click handler for this element
$element.on("click", function () {
var $content,
$input,
$button,
i;
if ($element.parent().parent().is(":nth-child(1)")) {
// newest first, so we have to go through
// the array backwards
$content = $("<ul>");
for (i = Task.length-1; i >= 1; i--) {
// $buttondelete = $("<buttonDelete>").text("X");
var txt1 = Task[i].toStringName();
var txt2 = Task[i].toStringDate();
var txt3 = Task[i].toStringType();
//alert(txt3);
$content.append('<li> <span class="itemLeft">'+txt1+'</span> <span class="itemMiddle">'+txt2+'</span> <span class="itemRight">'+txt3+'</span><b class="deleteIcon"> X </b>');
}
}
$("main .content").append($content);
return false;
});
});
If you are creating the items inside ul dynamically you should bind the click event like this :
$(".content").on("click", ".deleteIcon", function()
{
alert("clicked") ;
return false;
}
) ;
The class selector starts with a . (just like the example you say you have that works).
Try
$(".deleteIcon").on("click", function () {
alert("Oh, clicked!");
return false;
});

$('#div').bind('scroll' function({})) not working

I have added 2 codes here the window.scroll works on my example but not the second one binding the div to the scroll.
Any one knows what am I doing wrong!?
Just so you know I'm working in MeteorJS <- I dont think that this is the problem bc. the window scrolling works.
This 2 codes are in the same js file.
$(window).scroll(function() {
lastSession = Session.get('c_info')[Session.get('c_info').current]
if(lastSession.list == 0 && $(window).height() + $(window).scrollTop() >= $(document).height()){
lastItem = $( ".list-item div:last" ).html();
if (lastSession.page == 1){
currentSession().more();
lastItem2 = $( ".list-item div:last" ).html();
} else if( lastItem2 != lastItem) {
currentSession().more();
lastItem2 = $( ".list-item div:last" ).html()
}
}
});
$('#playlist').bind('scroll',function() {
console.log("div is scrolling");
});
I tried this too:
$('#playlist').scroll(function() {
console.log("div is scrolling");
});
MeteorJS Template:
<template name="playList">
<div id="playlist" class="playlist show-for-large-up">
{{#each list}}
<a href="/video/{{_id}}" class="large-12 columns" id="pl{{v_id}}">
<div>
<div class="large-7 columns plRight">
<span>{{vTitle}}</span>
</div>
</div>
</a>
{{/each}}
</div>
</template>
Also Tried:
$('#playlist').on('scroll',function() {console.log('test')});// not working
Tried to Change the id name and putting on the document ready:
$( document ).ready(function (){
$('#pl_list').bind('scroll',function() {
console.log("div is scrolling");
});
})//failed
The div has a scrollbar and the list is long and i have a css like this:
.playlist {
padding: 0;
overflow-y: scroll;
height: 458px;
}
Also tried:
Template.playList.rendered = function () {
console.log("playlist rendered");// i can see this on logs this tells that template is in doom
Meteor.setTimeout(function(){
$('#playlist').on('scroll',function(){
console.log('Scrolling...');
});
}, 2000);// with settimeout i have giveng it 2 more seconds
}
Try this out -
$(document).ready(function(){
$('#playlist').on('scroll',function(){
console.log('Scrolling...');
});
});
Use
$('#playlist').scroll(function() {
console.log("div is scrolling");
});
instead (like you did for window).
Thats the purpose of scroll(). See jquery documentation.
Scrolling event is fired on the element, if it has scrolled. So if you only scrolling the "body" element of the DOM it will not be triggered for #playlist.
So you have put a scrollbar to the container element of #playlist. Shot answer, cut the height and add a scrollbar, then the event will fire on it.
I did a Jsfiddle http://jsfiddle.net/34j0qnpg/4/
html
<div id="playlist-wrapper">
<div id="playlist" class="playlist show-for-large-up">
<a href="/video/1" class="large-12 columns" id="pl1">
<div>
<div class="large-7 columns plRight">
<span>Titel</span>
</div>
</div>
</a>
css part
body, html {
padding: 0;
margin: 0;
background-color: lightgrey;
color: #fff;
font-family: Arial;
height: 5000px;
overflow-y:scroll;
}
#stats {
position: relative;
}
#playlist-wrapper {
border: 1px solid #000;
padding: 10px;
height: 300px;
overflow-y: scroll;
}
#playlist {
height: 1000px;
background-color: darkgrey;
}
var $stats = $('#stats');
$('#playlist-wrapper').on('scroll', function() {
$stats.html('playlist scrolling');
console.log('playlist scrolling');
});
$(window).on('scroll', function() {
$stats.html('window scrolling');
console.log('window scrolling');
});
Solved with this code:
Tried it earlyer no results, after meteorjs project reset it just automagicly workded:
Template.playList.rendered = function () {
console.log("playlist rendered");
$('#playlist').on('scroll',function(){
console.log('Scrolling...');
});
}
I answered my question just if anybody is searching for the same answer.
Thanks to anybody who tried to help me.
I LOVE THIS COMMUNITY.

How can I change the x position of a div via javascript when I click on another div this way?

<body>
<div id = "SiteContainer">
<div id = "NavigationButtons"></div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition();">x</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition();">y</div>
<div id = "VideoWrapper">
<div id = "SlideShowItem">
<img src="Images/A.png" alt="A"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/B.png" alt="B"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/C.png" alt="C" ></img>
</div>
</div>
</div>
</div>
<script>
var wrapper = document.querySelector("#VideoWrapper");
function setPosition(e)
{
if(e.target.name = "forward")
{
if!(wrapper.style.left = "-200%")
{
wrapper.style.left = wrapper.style.left - 100%;
}
}
else
{
if(e.target.name = "back")
{
if!(wrapper.style.left = "0%")
{
wrapper.style.left = wrapper.style.left + 100%;
}
}
}
}
</script>
</body>
Hi, I am very new to javascript. What I am trying to do, is change the x-position of a div when another div (NavigationForward or NavigationBackward) is clicked. However it does not appear to do anything at all. Basically if the div with name forward is clicked, I want to translate the VideoWrapper -100% from it's current position and +100% when "back". The css div itself VideoWrapper has a width of 300%. Inside this div as you can see is a SlideShowItem which is what will change. Perhaps I am adding and subtracting 100% the wrong way?
EDIT:
Thanks everyone for helping me out with this...I had just one more query, I am trying to hide the arrows based on whether the wrapper is at the first slide or the last slide. If its on the first slide, then I'd hide the left arrow div and if it's on the last, I'd hide the right arrow, otherwise display both of em. Ive tried several ways to achieve this, but none of em work, so Ive resorted to using copies of variables from the function that works. Even then it does not work. It appears that my if and else if statements always evaluate to false, so perhaps I am not retrieving the position properly?
function HideArrows()
{
var wrapper2 = document.getElementById("VideoWrapper");
var offset_x2 = wrapper2.style.left;
if(parseInt(offset_x2,10) == max_x)
{
document.getElementById("NavigationForward").display = 'none';
}
else if(parseInt(offset_x2,10) == min_x)
{
document.getElementById("NavigationBackward").display = 'none';
}
else
{
document.getElementById("NavigationForward").display = 'inline-block';
document.getElementById("NavigationBackward").display = 'inline-block';
}
}
//html is the same except that I added a mouseover = "HideArrows();"
<div id = "ShowReelContainer" onmouseover="HideArrows();">
To achieve this type o slider functionality your div VideoWrapper must have overflow:hidden style, and your SlideShowItemdivs must have a position:relative style.
Then to move the slides forward or backward you can use the style left which allows you to move the divs SlideShowItem relative to it's parent VideoWrapper.
I've tested this here on JSFiddle.
It seems to work as you described in your question, although you may need to do some adjustments, like defining the width of your slides, how many they are and so on.
For the sake of simplicity, I defined them as "constants" on the top of the code, but I think you can work from that point on.
CSS
#VideoWrapper{
position:relative; height:100px; white-space:nowrap;width:500px;
margin-left:0px; border:1px solid #000; overflow:hidden; }
.SlideShowItem{
width:500px; height:100px;display:inline-block;position:relative; }
#NavigationForward, #NavigationBackward{
cursor:pointer;float:left; background-color:silver;margin-right:5px;
margin-bottom:10px; text-align:center; padding:10px; }
HTML
<div id = "SiteContainer">
<div id = "NavigationButtons">
</div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition('back');">prev</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition('forward');">next</div>
<div style="clear:both;"></div>
<div id = "VideoWrapper">
<div class= "SlideShowItem" style="background-color:blue;">
Slide 1
</div>
<div class = "SlideShowItem" style="background-color:yellow;">
Slide 2
</div>
<div class = "SlideShowItem" style="background-color:pink;">
Slide 3
</div>
</div>
</div>
</div>
JavaScript
var unit = 'px'; var margin = 4; var itemSize = 500 + margin; var itemCount = 3; var min_x = 0; var max_x = -(itemCount-1) * itemSize;
function setPosition(e) {
var wrapper = document.getElementById("VideoWrapper");
var slides = wrapper.getElementsByTagName('div');
var offset_x = slides[0].style.left.replace(unit, '');
var curr_x = parseInt(offset_x.length == 0 ? 0 : offset_x);
if(e == "forward")
{
if(curr_x <= max_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + -itemSize) + unit;
}
else if(e == "back")
{
if(curr_x >= min_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + itemSize) + unit;
} }
After you analyze and test the code, I don't really know what's your purpose with this, I mean, you maybe just playing around or trying to develop something for a personal project, but if you are looking for something more professional avoid to create things like sliders on your own, as there are tons of plugins like this available and well tested out there on the web.
Consider using jQuery with NivoSlider, it works like a charm and is cross browser.
I would recommend using jQuery, this will reduce your coding by quite a bit. Can read more here: http://api.jquery.com/animate/
I've created a simple fiddle for you to take a look at. This example uses the .animate() method to reposition two div elements based on the CSS 'left' property.
CSS:
#container {
position: absolute;
left: 1em;
top: 1em;
right: 1em;
bottom: 1em;
overflow: hidden;
}
#one, #two {
position: absolute;
color: white;
}
#one {
background: pink;
width: 100%;
top:0;
bottom:0;
}
#two {
background: blue;
width: 100%;
left: 100%;
top:0;
bottom:0;
}
HTML:
<div id="container">
<div id="one">Div One</div>
<div id="two">Div Two</div>
</div>
JavaScript/jQuery:
var one, two, container;
function animateSlides(){
one.animate({
left : '-100%'
}, 1000, function(){
one.animate({
left : 0
}, 1000);
});
two.animate({
left : 0
}, 1000, function(){
two.animate({
left:'100%'
}, 1000);
});
};
$(function(){
one = $('#one');
two = $('#two');
container = $('#container');
setInterval(animateSlides, 2000);
});
JSFiddle Example: http://jsfiddle.net/adamfullen/vSSK8/3/

Page navigation using jQuery slideUp() animation

I'm trying to create a multi-page navigation using jQuery, where when we change page the current one would suffer a slideUp() and disappear.
Until now I have this JS:
$(document).ready(function() {
current = "#div1";
$("#btn1").click(function() {
if (current != "#div1") {
$(current).slideUp("slow");
current = "#div1";
}
});
$("#btn2").click(function() {
if (current != "#div2") {
$(current).slideUp("slow");
current = "#div2";
}
});
$("#btn3").click(function() {
if (current != "#div3") {
$(current).slideUp("slow");
current = "#div3";
}
});
});
Running on this: http://jsfiddle.net/93gk3oyg/
I just can't seem to correctly navigate from page 1 to 3, 3 to 2, and so on...
Any help would be appreciated :)
I have refactored your code somewhat. I actually do not make any use of the slide-up functionality, everything is handled using CSS animations, which means you will be able to alter those to something else later. Also notice, that this means you don't really need to mess about with z-index.
HTML:
<div id="menu">
<button class="btn" id="btn1" data-rel-page="div1">Pag1</button>
<button class="btn" id="btn2" data-rel-page="div2">Pag2</button>
<button class="btn" id="btn3" data-rel-page="div3">Pag3</button>
<button class="btn" id="btn4" data-rel-page="div4">Pag4</button>
</div>
<div id="div1" class="fullscreen active">
<center>HOME</center>
</div>
<div id="div2" class="fullscreen">
<center>PAGE2</center>
</div>
<div id="div3" class="fullscreen">
<center>PAGE3</center>
</div>
<div id="div4" class="fullscreen">
<center>PAGE4</center>
</div>
JS:
$(document).ready(function () {
var current = "div1";
$("[data-rel-page]").bind('click', function (evt) {
var el = $(evt.currentTarget).attr('data-rel-page');
if (el === current) return;
var $el = $("#" + el);
var $cur = $("#" + current);
current = el;
$cur.removeClass('active');
$el.addClass('active');
})
});
CSS:
.fullscreen {
transition: all 0.4s linear;
position: fixed;
bottom: 0px;
left: 0px;
right: 0px;
height: 0%;
overflow: hidden;
}
.fullscreen.active {
display: block;
height: 100%;
}
Here is the fiddle: http://jsfiddle.net/93gk3oyg/9/

Categories

Resources