Use of this in javascript/Jquery - javascript

I have an anchor tag as below :
<a href='#' class='control_next_photo'>></a>
I have set an event on click of the above anchor as follows:
$('a.control_prev_photo').click(function () {
moveLeft();
return false;
});
Below is the moveLeft function.
function moveLeft() {
$('#post-text-slider ul').animate({
left: + slideWidth
}, 200, function () {
$('#post-text-slider ul li:last-child').prependTo('#post-text-slider ul');
$('#post-text-slider ul').css('left', '');
});
};
Now my concerns is that the above is working perfectly when there is only one "post-text-slider" DIV inside which we have an anchor tag. when a user is clicking on the anchor tag the moveLeft() is getting called which in turn moving the slide to left.
But actually, I have several "post-text-slider" DIVs inside which have their own anchor tag. Now in that case if a user clicks on the anchor tag, it will trigger the moveLeft() for all the "post-text-slider" which is not desirable.
Can someone please assist me with the solution for this.

If I figured out correctly your problem I suggest you:
convert post-text-slider from ID to class
use $(e.target).closest('div.post-text-slider') to get the current div
pass to moveLeft as argument the div element
var slideWidth = 100;
function oldMoveLeft() {
$('.post-text-slider ul').animate({
left: + slideWidth
}, 200, function () {
$('.post-text-slider ul li:last-child').prependTo('.post-text-slider ul');
$('.post-text-slider ul').css('left', '');
});
}
function moveLeft(element) {
var ulEle = element.find('ul');
ulEle.animate({
left: + slideWidth
}, 200, function () {
ulEle.find('li:last-child').prependTo(ulEle);
ulEle.css('left', '');
});
}
$(function () {
$('a.control_prev_photo').click(function (e) {
e.preventDefault();
moveLeft($(e.target).closest('div.post-text-slider'));
});
// old one
$('a.old').click(function () {
oldMoveLeft();
return false;
});
});
.post-text-slider {
width: 100%;
}
.control_prev_photo {
appearance: button;
-moz-appearance: button;
-webkit-appearance: button;
text-decoration: none; font: menu; color: ButtonText;
display: inline-block; padding: 2px 8px;
}
ul {
position: relative;
}
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<div class="post-text-slider">
<a class="control_prev_photo">Click Me</a>
<a class="control_prev_photo old">Old Click Me behoviour</a>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
</div>
<div class="post-text-slider">
<a class="control_prev_photo">Click Me</a>
<a class="control_prev_photo old">Old Click Me behoviour</a>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
</div>
<div class="post-text-slider">
<a class="control_prev_photo">Click Me</a>
<a class="control_prev_photo old">Old Click Me behoviour</a>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
</div>

Related

Dropdown Menu Closes On Hover (Error)

Whhenever I hover over the menu it works fine. But, when I try to get to the submenu links and children, the menu closes
/*----------------------------------------------------
/* Dropdown menu
/* ------------------------------------------------- */
jQuery(document).ready(function($) {
function mtsDropdownMenu() {
var wWidth = $(window).width();
if (wWidth > 865) {
$('#navigation ul.sub-menu, #navigation ul.children').hide();
var timer;
var delay = 100;
$('#navigation li').hover(
function() {
var $this = $(this);
timer = setTimeout(function() {
$this.children('ul.sub-menu, ul.children').slideDown('fast');
}, delay);
},
function() {
$(this).children('ul.sub-menu, ul.children').hide();
clearTimeout(timer);
}
);
} else {
$('#navigation li').unbind('hover');
$('#navigation li.active > ul.sub-menu, #navigation li.active > ul.children').show();
}
}
mtsDropdownMenu();
$(window).resize(function() {
mtsDropdownMenu();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="menu-item-513" class="menu-item "><i class="fa fa-calculator"></i> OFFERTE AANVRAGEN
<ul class="sub-menu">
<li id="menu-item-1146" class="menu-item">Zonnepanelen installatie (Belgiƫ)
</li>
<li id="menu-item-1144" class="menu-item">Zonnepanelen reinigen (Belgiƫ)
</li>
<li id="menu-item-1145" class="menu-item">Zonnepanelen installatie (Nederland)
</li>
</ul>
</li>
The code you posted works just fine; here's a plnkr to prove it: https://plnkr.co/edit/IFaueUhKE3J1K9vY1NkQ?p=preview
(simply wrapped a <div id='navigation'><ul> round the top li).
If you still loose the hover over the child-elements, it's caused by something you're not showing in the original question. E.g. adding this css:
li.menu-item {
position: relative;
top: 50px;
left: 300px;
}
would make it difficult to reach the child items because you, briefly, lose the parent-hover while moving to the child.

jQuery: How to make clicking anywhere outside of left menu close said window?

There is a menu button on the left of my site in progress.
This is the Javascript code which opens the menu:
var main = function()
$('.icon-menu').click(function() {
$('.menu').animate({
left: "0px"
}, 400);
$('body').animate({
left: "285px"
}, 400);
});
And this is the Javascript code which closes the menu:
$('.icon-close').click(function () {
$('.menu').animate({
left: "-285px"
}, 400);
$('body').animate({
left: "0px"
}, 400);
});
What I would like to be able to do is, instead of using a "close" icon, I would like for a click anywhere on the page (including the original menu button) to close the menu.
As the code is currently written, when the menu is opened/closed, it slides in from the left, and the main body of the page slides to the right the same amount of pixels, and vice-versa when closed.
EDIT:
Here's the skeleton of the HTML as requested:
<div class="menu">
<div class="icon-close">
<img src="close.png">
</div>
<ul>
<li>Home
</li>
<li>Gallery
</li>
<li>Locations
</li>
<li>Contact Us
</li>
</ul>
</div>
<div class="jumbotron">
<div class="icon-menu">
<i class="fa fa-bars"></i>Menu
</div>
</div>
You can capture a document.onclick event then check the event target id against a set of allowed id's Note that to do this you have to add id attributes to the close button and the "body". I've also taken the liberty of adding an id to the menu and a wrapper around the "body" of the document and changed your body tag animation to that wrapper, as you shouldnt move the body tag directly. Note that to resize the body on menu open just change the body position: absolute and set right: 0px;
(Demo keep body size on menu open)
(Demo resize body to keep within viewport on menu open)
$(document).on('click', function(e) {
if ($("#menu").position().left != '0') {
if (e.target.id === "open") {
$('#menu').animate({
left: "0px"
}, 400);
$('#body').animate({
left: "285px"
}, 400);
}
} else {
if (e.target.id === "body" || e.target.id === "close" || e.target.id === "open") {
$('#menu').animate({
left: "-285px"
}, 400);
$('#body').animate({
left: "0px"
}, 400);
}
}
});
html, body, #menu, #body {
height: 100%;
}
.menu {
position: absolute;
width: 285px;
left: -285px;
}
#body {
position: relative;
left: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu" id="menu">
<div class="icon-close">
<img src="close.png" id="close">
</div>
<ul>
<li>Home
</li>
<li>Gallery
</li>
<li>Locations
</li>
<li>Contact Us
</li>
</ul>
</div>
<div id="body">
<div class="jumbotron">
<div class="icon-menu" id="open">
<i class="fa fa-bars" id="open"></i>Menu
</div>
</div>
</div>
Pure JS and CSS
The following is a pure javascript and css method for achieving the same effect. I'm including this for reference as it is a lot lighter weight than including jquery, however if you have jquery included already there is no reason to not use the jquery methods. Notice that on older browsers that do not support css transitions the menu will still open but will not be animated (which is a good thing for older browsers as javascript animations can slow things down quite a bit)
(Demo keep body size on menu open)
(Demo resize body to keep within viewport on menu open)
var menu = document.getElementById("menu");
var body = document.getElementById("body");
menu.style.transition = "0.3s linear";
body.style.transition = "0.3s linear";
document.onclick = function(e) {
if (menu.style.left != "0px") {
if (e.target.id === "open") {
menu.style.left = "0px";
body.style.left = "285px";
}
} else {
if (e.target.id === "body" || e.target.id === "close" || e.target.id === "open") {
menu.style.left = "-285px";
body.style.left = "0px";
}
}
};
html, body, #menu, #body {
height: 100%;
}
.menu {
position: absolute;
width: 285px;
left: -285px;
}
#body {
position: relative;
left: 0px;
}
<div class="menu" id="menu">
<div class="icon-close">
<img src="close.png" id="close">
</div>
<ul>
<li>Home
</li>
<li>Gallery
</li>
<li>Locations
</li>
<li>Contact Us
</li>
</ul>
</div>
<div id="body">
<div class="jumbotron">
<div class="icon-menu" id="open">
<i class="fa fa-bars" id="open"></i>Menu
</div>
</div>
</div>
Here's humble's version of the snippet below:
http://jsfiddle.net/humbleRumble/3j7s9ggz/
You can just bind a click event to the document that does the same thing as the click on the close button:
$(document).on('click', function (e) {
// Filter some elements out so that this function doesn't
// execute when it's not intended to.
var target = e.target,
isMenuElem = $(target).parents('.menu').length || $(target).is('.menu'),
isMenuClose = $('.icon-close').has(target).length,
isIconMenu = $(target).is('.icon-menu');
// Simply return if the clicked element falls under the filter.
// This allows the close button to close,
// the menu to not close itself if you click its body,
// the function to not interfere with the menu button functionality,
// and that a click on anywhere will close the menu.
if (isMenuElem && !isMenuClose || isIconMenu) return;
$('.menu, #jumbotron').animate({
left: "-285px"
}, 400);
});
$('.icon-menu').click(function () {
// This is a 'toggle' value for left,
// if the menu is opened (left: 0), close it (left: -285)
// and vice-versa.
var toggleAnim = $('.menu').css('left') === '-285px' ? 0 : '-285px';
$('.menu, #jumbotron').animate({
// Apply the toggle
left: toggleAnim
}, 400);
});
html, body {
padding: 0;
margin: 0;
}
#jumbotron {
position: relative;
height: 500px;
width: 300px;
float: left;
}
.menu {
position: relative;
width: 285px;
height: 500px;
background: red;
float: left;
}
.icon-menu {
background: black;
color: #fff;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
<div class="icon-close">
<img src="close.png" alt="Close Me">
</div>
<ul>
<li>Home
</li>
<li>Gallery
</li>
<li>Locations
</li>
<li>Contact Us
</li>
</ul>
</div>
<div class="jumbotron" id="jumbotron">
<div class="icon-menu">
<i class="fa fa-bars"></i>Menu
</div>
</div>
This will trigger with a click anywhere on the page, but not on the elements inside of the menu (except the close button).

Add scroll animation to list in jQuery

I have a list where if you click prev next it goes left and right as shown in this fiddle
HTML
<div>
<span id="prev">prev</span>
<ul id="scrolllist">
<li><img src="http://dummyimage.com/100x100/000000/fff"></li>
<li><img src="http://dummyimage.com/100x100/f33636/fff"></li>
<li><img src="http://dummyimage.com/100x100/0c5b9e/fff"></li>
<li><img src="http://dummyimage.com/100x100/0c9e0c/fff"></li>
</ul>
<span id="next">next</span>
</div>
CSS
div {
float: left;
width: 550px;
}
li {
float: left;
list-style-type: none;
margin: 0 5px;
}
#prev {
cursor: pointer;
float: left;
}
#next {
cursor: pointer;
float: right;
}
JS
$(function () {
$('#prev').click(function () {
var first = $('#scrolllist li:first-child');
$('#scrolllist li').parent().append(first).animate({ "left": "-=50px" }, "slow" );
});
$('#next').click(function () {
var last = $('#scrolllist li:last');
$('#scrolllist li').parent().prepend(last).animate({ "left": "+=50px" }, "slow" );
});
});
This works moves them across as expected however I want to scroll the list items across to get the affect of them going in the clicked direction similar to what can be seen in http://coolcarousels.frebsite.nl/c/58/
What do I need to do to get this working?
The trick to doing it right is to place the images in a hidden container div and then animate that container to the left or right as needed, cloning the first or last img in the list and then appending or prepending depending on the direction.
The img container div must be placed inside another div with an explicit height and width with overflow set to hidden. This prevents the wide img container from being visible to the user.
Here is the HTML:
<div>
<span id="prev">prev</span>
<div class="scroll-container">
<div class="img-container">
<img src="http://dummyimage.com/100x100/000000/fff">
<img src="http://dummyimage.com/100x100/f33636/fff">
<img src="http://dummyimage.com/100x100/0c5b9e/fff">
<img src="http://dummyimage.com/100x100/0c9e0c/fff">
</div>
</div>
<span id="next">next</span>
And the JavaScript:
$(function () {
$('#prev').click(function () {
if(!$('.img-container').is(':animated')) {
var first = $('.img-container img:first-child');
var firstClone = first.clone();
$('.img-container').append(firstClone);
$('.img-container').animate({ "left": "-=110px" }, "slow", function() {
first.remove();
$('.img-container').css("left", "0");
});
}
});
$('#next').click(function () {
if(!$('.img-container').is(':animated')) {
var last = $('.img-container img:last-child');
var lastClone = last.clone();
$('.img-container').css("left", "-110px");
$('.img-container').prepend(lastClone);
$('.img-container').animate({ "left": "0" }, "slow", function() {
last.remove();
});
}
});
});
Note the 'if not animated' check at the beginning of each function. This prevents the user from running the functions again before the animation has completed (which would cause weird errors).
Here is a modified version of your fiddle: http://jsfiddle.net/fJqKV/17/

How to activate menu tab after refreshing

How can I activate a menu tab after refreshing?
Here are my code
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<style>
.menu{width: 600px; height: 25; font-size: 18px;}
.menu li{list-style: none; float: left; margin-right: 4px; padding: 5px;}
.menu li:hover, .menu li.active {
background-color: #f90;
}
</style>
</head>
<body>
<ul class="menu">
<li><a href='#'>One</a></li>
<li><a href='#'>Two</a></li>
<li><a href='#'>Three</a></li>
<li><a href='#'>Four</a></li>
</ul>
<script type="text/javascript">
var make_button_active = function()
{
//Get item siblings
var siblings =($(this).siblings());
//Remove active class on all buttons
siblings.each(function (index)
{
$(this).removeClass('active');
}
)
//Add the clicked button class
$(this).addClass('active');
}
//Attach events to menu
$(document).ready(
function()
{
$(".menu li").click(make_button_active);
}
)
</script>
Can anyone tell me How to resolve this issue ?
Just like #Johan said, store your last active tab in a localStorage or cookie. Since there is no noticeable difference in performance between the two. I suggest you use localStorage because it's much easier to use. Like this:
function make_button_active(tab) {
//Get item siblings
var siblings = tab.siblings();
//Remove active class on all buttons
siblings.each(function(){
$(this).removeClass('active');
})
//Add the clicked button class
tab.addClass('active');
}
//Attach events to menu
$(document).ready(function(){
if(localStorage){
var ind = localStorage['tab']
make_button_active($('.menu li').eq(ind));
}
$(".menu li").click(function () {
if(localStorage){
localStorage['tab'] = $(this).index();
}
make_button_active($(this));
});
});
Check out this fiddle.

Change background color on anchor in listitem when clicked

I have menu constructed by ul li with anchor tags in each. Css is applied to the anchor
and anchor:hover however I want the selected item to show that it is selected be changing the background a different color. anchor:active does not work.
I am trying javascript but not yet successful. Can this be soley done through css? I have looked at so many examples, but none actually worked right.
JAVASCRIPT
<script type="text/javascript">
function ChangeColor(obj) {
var li = document.getElementById(obj.id);
li.style.background = "#bfcbd6";
}
</script>
HTML
<div id="navigation">
<ul>
<li><a onclick="changecolor(this);" href="Default.aspx">Home</a></li>
<li><a onclick="changecolor(this);" href="View.aspx">View</a></li>
<li><a onclick="changecolor(this);" href="About.aspx">About</a></li>
</ul>
</div>
CSS - Simplified
#navigation ul {
list-style-type: none;
}
#navigation li
{
float: left;
}
#navigation a
{
background-color: #465c71;
}
#navigation a:hover
{
background-color: #bfcbd6;
}
you don't need to get id again for handling element. obj references the actual element.
<script type="text/javascript">
function ChangeColor(obj) {
obj.style.backgroundColor = "#bfcbd6";
}
</script>
Edit: And javaScript is case sensitive, so you should check your function names.
Here is a jsFiddle Demo
I have found a way to use JavaScript to solve this situation. This works for having MasterPage. Changing the id of the selected tab will then reference the css for that
selected tab only while setting the other tabs id's to null.
HTML
<div id="navbar">
<div id="holder">
<ul id="menulist">
<li><a onclick="SelectedTab(this);" href="#" id="onlink" >Home</a></li>
<li><a onclick="SelectedTab(this);" href="#" id="" >Products</a></li>
<li><a onclick="SelectedTab(this);" href="#" id="">Services</a></li>
<li><a onclick="SelectedTab(this);" href="#" id="">Gallery</a></li>
<li><a onclick="SelectedTab(this);" href="#" id="" >Contact</a></li>
</ul>
</div>
</div>
JavaScript
function SelectedTab(sender) {
var aElements = sender.parentNode.parentNode.getElementsByTagName("a");
var aElementsLength = aElements.length;
var index;
for (var i = 0; i < aElementsLength; i++)
{
if (aElements[i] == sender) //this condition is never true
{
index = i;
aElements[i].id="onlink"
} else {
aElements[i].id=""
}
}
}
Css for changing the background color after tab has been selected
#holder ul li a#onlink
{
background: #FFF;
color: #000;
border-bottom: 1px solid #FFF;
}

Categories