How to shorten this code? - javascript

I'm trying to create on() mouseenter function for each element, but is there any way to shorten that function somehow. The problem is that I've created that on mouseenter function several times. Please help guys :)
This is the code below
var $member1 = $('.team-content img:nth-child(1)'),
$member2 = $('.team-content img:nth-child(2)'),
$member3 = $('.team-content img:nth-child(3)'),
$member4 = $('.team-content img:nth-child(4)')
$(".member1").on('mouseenter', function() {
$member1.css({
"left": "0px"
});
}).on('mouseleave', function() {
$member1.css({
"left": ""
});
});
$(".member2").on('mouseenter', function() {
$member2.css({
"left": "0px"
});
}).on('mouseleave', function() {
$member2.css({
"left": ""
});
});
$(".member3").on('mouseenter', function() {
$member3.css({
"left": "0px"
});
}).on('mouseleave', function() {
$member3.css({
"left": ""
});
});
$(".member4").on('mouseenter', function() {
$member4.css({
"left": "0px"
});
}).on('mouseleave', function() {
$member4.css({
"left": ""
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="team" class="about-team">
<div class="team-header">
<h2 class="team-text">Our Team</h2>
<div class="divider"></div>
</div>
<div class="section-content">
<div class="row text-center">
<div class="col-xs-6 col-md-3 col-lg-3 member1">
<h2 class="t-seperator">John Doe</h2>
<span>/CEO</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member2">
<h2 class="t-seperator">Jesica Ice</h2>
<span>/DESIGNER</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member4">
<h2 class="t-seperator">Anna Moon</h2>
<span>/MARKETER</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member3">
<h2 class="t-seperator">Michael Huge</h2>
<span>/DEVELOPER</span>
</div>
</div>
</div>
</div>
<div id="main-team" class="team-content">
<img src="assets/img/team/team1.jpeg" alt="Team 1">
<img src="assets/img/team/team2.jpg" alt="Team 2">
<img src="assets/img/team/team3.jpg" alt="Team 3">
<img src="assets/img/team/team4.jpg" alt="Team 4">
</div>

You can add a general handler and apply the function on the corresponding .member* element if you detect the index of the hovered img using the index() function, Here is an example: (In the example I change the color just for clarity)
$(".team-content img").on('mouseenter', function(e) {
var imageIndex = $(".team-content img").index(e.target) + 1;
$(".member" + imageIndex).css({
"color": "red"
});
}).on('mouseleave', function(e) {
var imageIndex = $(".team-content img").index(e.target) + 1;
$(".member" + imageIndex).css({
"color": "black"
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="team" class="about-team">
<div class="team-header">
<h2 class="team-text">Our Team</h2>
<div class="divider"></div>
</div>
<div class="section-content">
<div class="row text-center">
<div class="col-xs-6 col-md-3 col-lg-3 member1">
<h2 class="t-seperator">John Doe</h2>
<span>/CEO</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member2">
<h2 class="t-seperator">Jesica Ice</h2>
<span>/DESIGNER</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member4">
<h2 class="t-seperator">Anna Moon</h2>
<span>/MARKETER</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member3">
<h2 class="t-seperator">Michael Huge</h2>
<span>/DEVELOPER</span>
</div>
</div>
</div>
</div>
<div id="main-team" class="team-content">
<img src="assets/img/team/team1.jpeg" alt="Team 1">
<img src="assets/img/team/team2.jpg" alt="Team 2">
<img src="assets/img/team/team3.jpg" alt="Team 3">
<img src="assets/img/team/team4.jpg" alt="Team 4">
</div>

You can just use a loop to get them all done at once!
for (var i = 1; i <= 4; i++) {
$('.member' + i).on('mouseenter', function() {
$('.team-content img:nth-child(' + i + ')').css({'left': '0px'});
}).on('mouseleave', function() {
$('.team-content img:nth-child(' + i + ')').css({'left': ''});
});
}

I may have over-thought it, but if the member number and the nth-child number are the same, why not use that to create the relevant accessor? I've got three functions here: the first runs on initialization and saves the integer portion of the member number as a data attribute for later retrieval. The mouseenter and mouseleave functions retrieve that saved member number, and build the selector using that.
$("div[class*='member']").each(function() {
// for every member element, let's save its
// relevant nth-child number.
var myNumber = 0;
var myClasses = $(this).prop("class").split(" ");
// check all classes to find the member number
for (var i = 0; i <= myClasses.length; i++) {
if ( myClasses[i].startsWith("member") ) {
// strip out JUST the number portion.
myNumber = myClasses[i].match(/\d+/)[0];
}
if( myNumber != 0 )
break;
}
// Save the number portion for later.
$(this).data("nthNumber", myNumber);
}).on('mouseenter', function() {
// retrieve the saved number
var selector = ".team-content img:nth-child("+ $(this).data("nthNumber") +" )";
$(selector).show();
}).on('mouseleave', function() {
// retrieve the saved number
var selector = ".team-content img:nth-child("+ $(this).data("nthNumber") +" )";
$(selector).hide();
});
.about-team {
width: 400px;
float: left;
}
.team-content {
position: absolute;
right: 5px;
top: 5px;
}
.team-content img {
display: none;
border: 1px dotted red;
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="team" class="about-team">
<div class="team-header">
<h2 class="team-text">Our Team</h2>
<div class="divider"></div>
</div>
<div class="section-content">
<div class="row text-center">
<div class="col-xs-6 col-md-3 col-lg-3 member1">
<h2 class="t-seperator">John Doe</h2>
<span>/CEO</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member2">
<h2 class="t-seperator">Jesica Ice</h2>
<span>/DESIGNER</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member4">
<h2 class="t-seperator">Anna Moon</h2>
<span>/MARKETER</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member3">
<h2 class="t-seperator">Michael Huge</h2>
<span>/DEVELOPER</span>
</div>
</div>
</div>
</div>
<div id="main-team" class="team-content">
<img src="assets/img/team/team1.jpeg" alt="Team 1">
<img src="assets/img/team/team2.jpg" alt="Team 2">
<img src="assets/img/team/team3.jpg" alt="Team 3">
<img src="assets/img/team/team4.jpg" alt="Team 4">
</div>
So a few changes made: first, I'd left the initial selector wrong. Then, I added some CSS styles so we could see something happening. The advantage of this approach (while it may be longer) is that it's extensible. If you add thirty more employees, you'd have to create a variable for each one, and use that each time. By this approach, it's happening automatically.

Related

How can I store a string without duplicating it?

There are 2 cards panels, and I would like to change the image of the card when I hover over it, then when I leave it I want to come back to the initial image.
First time it works for each image, but when I try to hover second time it duplicates my string where I store the path..
HTML CODE
<div class="col-lg d-flex justify-content-center mb-4">
<div class="card border-0"">
<img src="img/slide-1.jpg" class=" card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Image 1</h5>
</div>
</div>
</div>
<div class="col-lg d-flex justify-content-center mb-4">
<div class="card border-0"">
<img src="img/slide-1.jpg" class=" card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Image 2</h5>
</div>
</div>
</div>
JQUERY CODE
(function ($) {
"use strict"; // Start of use strict
var image_product;
var image_product_path="/Users/paul/Desktop/Site/";
$(".card-img-top").on({
mouseenter: function () {
image_product = $(this).attr("src");
$(this).attr("src","/Users/paul/Desktop/Site/img/slide-3.jpg");
},
mouseleave: function () {
$(this).attr("src",image_product_path+image_product);
}
});
})(jQuery); // End of use strict
The error that is triggered second time when I try to hover over the cards:
[Error] Not allowed to load local resource: file:///Users/paul/Desktop/Site//Users/paul/Desktop/Site/img/slide-1.jpg
The error that is triggered third time when I try to hover over the cards:
[Error] Not allowed to load local resource: file:///Users/paul/Desktop/Site//Users/paul/Desktop/Site//Users/paul/Desktop/Site//Users/paul/Desktop/Site/img/slide-1.jpg
AND SO ON
There are n cards panels, and I would like to change the image of the
card when I hover over it, then when I leave it I want to come back to
the initial image.
Set the original image into a data attribute, then on mouse out switch it back.
(function($) {
$(".card-img-top").on({
mouseenter: function() {
$(this).data('original', $(this).attr("src"));
$(this).attr("src", "https://via.placeholder.com/300/09f/000.png");
},
mouseleave: function() {
$(this).attr("src", $(this).data('original'));
}
});
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg d-flex justify-content-center mb-4">
<div class="card border-0">
<img src="https://via.placeholder.com/300/09f/fff.png" class=" card-img-top " alt="... ">
<div class="card-body ">
<h5 class="card-title ">Image 1</h5>
</div>
</div>
</div>
If you want a different image for each different card then set it into a data attribute.
(function($) {
$(".card-img-top").on({
mouseenter: function() {
$(this).data('original', $(this).attr("src"));
$(this).attr("src", $(this).data('hover-image'));
},
mouseleave: function() {
$(this).attr("src", $(this).data('original'));
}
});
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg d-flex justify-content-center mb-4">
<div class="card border-0">
<img src="https://via.placeholder.com/100/09f/fff.png" data-hover-image="https://via.placeholder.com/100/09f/000.png" class=" card-img-top " alt="... ">
<div class="card-body ">
<h5 class="card-title ">Image 1</h5>
</div>
</div>
</div>
<div class="col-lg d-flex justify-content-center mb-4">
<div class="card border-0">
<img src="https://via.placeholder.com/100/07f/aaa.png" data-hover-image="https://via.placeholder.com/100/05f/333.png" class=" card-img-top " alt="... ">
<div class="card-body ">
<h5 class="card-title ">Image 2</h5>
</div>
</div>
</div>
Here's what the src attribute and your image_product variable contain at the different phases:
Phase
src
image_product
before first run
img/slide-1.jpg
undefined
first mouseenter
/Users/paul/Desktop/Site/img/slide-3.jpg
img/slide-1.jpg
first mouseleave
/Users/paul/Desktop/Site/img/slide-1.jpg
img/slide-1.jpg
2nd mouseenter
/Users/paul/Desktop/Site/img/slide-3.jpg
/Users/paul/Desktop/Site/img/slide-3.jpg
2nd mouseleave
/Users/paul/Desktop/Site/Users/paul/Desktop/Site/img/slide-1.jpg
/Users/paul/Desktop/Site/img/slide-3.jpg
In your handlers functions, you keep storing whatever is in src into image_product when the mouse enters.
The second time you mouseenter, image_product already contains the full path, but in your mouseleave function you keep prepending the path every time.
Please check a link
https://stackoverflow.com/a/18032363/3526623
The solution from the link above without Jquery
function hover(element) {
element.setAttribute('src', 'http://dummyimage.com/100x100/eb00eb/fff');
}
function unhover(element) {
element.setAttribute('src', 'http://dummyimage.com/100x100/000/fff');
}
<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover="hover(this);" onmouseout="unhover(this);" />

Animated counters on scroll not all loading

I have wrote the code below to get animated counters starting when visible on the window. It works well when the counters are all visible on the same row, but if only the first one is visible, this one will start the animation, but the others won't even if we scroll down. The first one is complete, but the others remain to zero.
/* SCROLL FUNCTIONS */
// Every time the window is scrolled...
$(window).scroll(function() {
// Check the location of each desired element
$('.counter').each(function(i) {
var bottom_of_object = $(this).offset().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
// If the object is completely visible in the window, fade it it
if (bottom_of_window > bottom_of_object) {
var $this = $(this);
$({
Counter: 0
}).animate({
Counter: $this.attr('data-to')
}, {
duration: 2000,
easing: 'swing',
step: function() {
$this.text(Math.ceil(this.Counter));
},
complete() {
$this.text(Math.ceil(this.Counter));
}
});
$(window).off("scroll");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col">
<div class="row counters text-dark">
<div class="col-sm-6 col-lg-3 mb-4 mb-lg-0">
<div class="counter" data-to="30000">0</div>
<label>Happy Clients</label>
</div>
<div class="col-sm-6 col-lg-3 mb-4 mb-lg-0">
<div class="counter" data-to="15">0</div>
<label>Years in Business</label>
</div>
<div class="col-sm-6 col-lg-3 mb-4 mb-sm-0">
<div class="counter" data-to="352">0</div>
<label>Cups of Coffee</label>
</div>
<div class="col-sm-6 col-lg-3">
<div class="counter" data-to="178">0</div>
<label>High Score</label>
</div>
</div>
</div>
</div>
The problem is this line of code:
$(window).off("scroll");
Your off call unbinds all events, not just one. That means all scroll event bindings are lost after the first number animation executes.
To solve this, you need to bind and unbind each number's animation separately. A simple way to do this would be to have a different function for each number animation and bind/unbind them separately. A generic example:
var myScroll1 = function () {
$(window).off("scroll", myScroll1)
}
$(window).on("scroll", myScroll1)
Notice we are turning on and off just this specific function reference. You can have 4 of them and switch them on and off separately.
EDIT: Here's your script modified to work as explained:
var anim1 = function () { animateAndKill(1, $("#n1"), 3000, anim1); }
var anim2 = function () { animateAndKill(2, $("#n2"), 15, anim2); }
var anim3 = function () { animateAndKill(3, $("#n3"), 352, anim3); }
var anim4 = function () { animateAndKill(4, $("#n4"), 178, anim4); }
// Every time the window is scrolled...
function animateAndKill(id, $number, max, myFunction) {
var bottom_of_object = $number.offset().top + $number.outerHeight();
var bottom_of_window = $(window).scrollTop() + window.innerHeight;
// If the object is completely visible in the window, fade it it
if (bottom_of_window > bottom_of_object) {
$({ Counter: 0 }).animate({ Counter: max }, {
duration: 2000,
easing: 'swing',
step: function () {
var n = Math.ceil(this.Counter);
$number.html(n);
}
});
$(window).off("scroll", myFunction);
}
}
$(window).on("scroll", anim1);
$(window).on("scroll", anim2);
$(window).on("scroll", anim3);
$(window).on("scroll", anim4);
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="code.js"></script>
</head>
<body>
<div style="height: 1000px; background: #33FF44"></div>
<div class="row" style="z-index: 100; font-size: 100px;">
<div class="col">
<div class="row counters text-dark">
<div class="col-sm-6 col-lg-3 mb-4 mb-lg-0">
<div id="n1" class="counter" data-to="30000">0</div>
<label>Happy Clients</label>
</div>
<div class="col-sm-6 col-lg-3 mb-4 mb-lg-0">
<div id="n2" class="counter" data-to="15">0</div>
<label>Years in Business</label>
</div>
<div class="col-sm-6 col-lg-3 mb-4 mb-sm-0">
<div id="n3" class="counter" data-to="352">0</div>
<label>Cups of Coffee</label>
</div>
<div class="col-sm-6 col-lg-3">
<div id="n4" class="counter" data-to="178">0</div>
<label>High Score</label>
</div>
</div>
</div>
</div>
<div style="height: 3000px; background: #33FF44"></div>
</body>
</html>
https://jsfiddle.net/tyddlywink/pdvh4b3n/
Get rid of the $(window).off("scroll");bit. And keep track of who's already been counted or not.
<div class="row">
<div class="col">
<div class="row counters text-dark">
<div class="col-sm-6 col-lg-3 mb-4 mb-lg-0">
<div class="counter" data-to="30000" data-counted='false'>0</div>
<label>Happy Clients</label>
</div>
<div style="height: 750px">
</div>
<div class="col-sm-6 col-lg-3 mb-4 mb-lg-0">
<div class="counter" data-to="15" data-counted='false'>0</div>
<label>Years in Business</label>
</div>
<div style="height: 750px">
</div>
<div class="col-sm-6 col-lg-3 mb-4 mb-sm-0">
<div class="counter" data-to="352" data-counted='false'>0</div>
<label>Cups of Coffee</label>
</div>
<div style="height: 750px">
</div>
<div class="col-sm-6 col-lg-3">
<div class="counter" data-to="178" data-counted='false'>0</div>
<label>High Score</label>
</div>
</div>
</div>
</div>
Javascript:
// Every time the window is scrolled...
$(window).scroll(function() {
// Check the location of each desired element
$('.counter').each(function(i) {
var bottom_of_object = $(this).offset().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
var counted = $(this).data("counted");
// If the object is completely visible in the window, fade it it
if (!counted && bottom_of_window > bottom_of_object) {
$(this).data("counted", true);
var $this = $(this);
$({
Counter: 0
}).animate({
Counter: $this.attr('data-to')
}, {
duration: 2000,
easing: 'swing',
step: function() {
$this.text(Math.ceil(this.Counter));
},
complete() {
$this.text(Math.ceil(this.Counter));
}
});
}
});
});
/*
SCROLL FUNCTIONS
********************************/
// Every time the window is scrolled...
$(window).scroll(function () {
// Check the location of each desired element
$('.count').each(function (i) {
var bottom_of_object = $(this).offset().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
// If the object is completely visible in the window, fade it it
if (bottom_of_window > bottom_of_object) {
var $this = $(this);
$({
Counter: 0
}).animate({
Counter: $this.attr('data-to')
}, {
duration: 2000,
easing: 'swing',
step: function () {
$this.text(Math.ceil(this.Counter));
},
complete(){
$this.text(Math.ceil(this.Counter));
}
});
$(this).removeClass('count').addClass('counted');
}
});
});
<div class="row">
<div class="col">
<div class="row counters text-dark">
<div class="col-sm-6 col-lg-3 mb-4 mb-lg-0">
<div class="count" data-to="30000">0</div>
<label>Happy Clients</label>
</div>
<div class="col-sm-6 col-lg-3 mb-4 mb-lg-0">
<div class="count" data-to="15">0</div>
<label>Years in Business</label>
</div>
<div class="col-sm-6 col-lg-3 mb-4 mb-sm-0">
<div class="count" data-to="352">0</div>
<label>Cups of Coffee</label>
</div>
<div class="col-sm-6 col-lg-3">
<div class="count" data-to="178">0</div>
<label>High Score</label>
</div>
</div>
</div>
</div>
Listening to scroll event is not performance friendly, you should really consider using Intersection Observer for stuff like this.
First you have to create a new observer:
var options = {
rootMargin: '0px',
threshold: 1.0
}
var observer = new IntersectionObserver(callback, options);
Here we define that once your target Element is 100% visible in the viewport (threshold of 1) your callback Function is getting executed. Here you can define another percentage, 0.5 would mean that the function would be executed once your element is 50% visible.
Then you have to define which elements to watch, in your case this would be the counter elements:
var target = document.querySelector('.counter');
observer.observe(target);
Last you need to specify what should happen once the element is visible in your viewport by defining the callback function:
var callback = function(entries, observer) {
entries.forEach(entry => {
// Each entry describes an intersection change for one observed
// here you animate the counter
});
};
In your specific case you probably won't run into performance problems but if you have more and more elements you will start to notice something. So it's better to know of this and to "do it right" if you come across this problem again.
If you need to support older browsers, use the official polyfill from w3c.
You can also remove the observer from any element if you don't need element where

Filter users by data-attribute Jquery

I am trying to filter users by its data attribute , I have main div called user-append which contains users that I get from ajax get request , there can be 3 users or 100 users, its dynamical , this is my div with one user for the moment
<div id="user-append">
<div class="fc-event draggable-user" data-profesion="'+user.profesion+'" id="user_'+user.id+'" style="z-index: 9999;">
<div class="container-fluid">
<input type="hidden" value="'+user.id+'" id="user_'+ user.id + '_value" class="userId">
<div class="row" style="justify-content: center;">
<div class="col-xs-3 avatar-col">
<div class="innerAvatarUserLeft">
<img src="'+getUserImage(user.avatar)+'" width="100%" style="margin: 0 auto;">
</div>
</div>
<div class="col-xs-9 data-col">
<p class="fullName dataText">'+user.fullName+'</p>
<p class="usr_Gender dataText">Male</p>
<div style="position: relative">
<li class="availableUnavailable"></li>
<li class="usr_profesion dataText">AVAILABLE</li>
</div>
<p class="user_id" style="float:right;margin: 3px">'+user.employee_id+'</p>
</div>
</div>
</div>
</div>
</div>
as you can see I have data-profesion attribute from which I am trying to filter users depend on the profession that they have , I get the ajax request like this
$.ajax({
url: "/rest/users",
success: function (users) {
var options = [];
$user = $("#append_users");
$.each(users, function (i, user) {
options.push({
'profession': user.prof.Profession,
'gender': user.prof.Gender
});
userArr.push({
'id': user.id,
'firstName': user.prof.FirstName,
'lastName': user.prof.LastName,
'fullName': user.prof.FirstName + ' ' + user.profile.LastName,
'email': user.email,
'avatar': user.prof.Photo,
'profesion': user.prof.Profession
});
$('#filterByProfession').html('');
$('#filterByGender').html(''); // FIRST CLEAR IT
$.each(options, function (k, v) {
if (v.profession !== null) {
$('#filterByProfession').append('<option>' + v.profession + '</option>');
}
if (v.gender !== null) {
$('#filterByGender').append('<option>' + v.gender + '</option>');
}
});
});
});
and now I am trying to filter the users by its data-profesion, on change of my select option which I populate from the ajax get request , It should show only the users that contain that data-profesion value , something like this
$('#filterByProfession').change(function () {
var filterVal = $(this).val();
var userProfVal = $(".fc-event").attr("data-profesion");
if (filterVal !== userProfVal) {
}
});
You can use a CSS selector to find those users, and then hide them:
$('#filterByProfession').change(function () {
// first hide ALL users
$('.draggable-user').hide()
// then filter out the ones with the correct profession:
// (you need to escape the used quote)
.filter('[data-profesion="' + $(this).val().replace(/"/g, '\\"') + '"]')
// ... and show those
.show();
});
You're trying to get the userProfVal throughout a className selector which can return more than one element.
var userProfVal = $(".fc-event").attr("data-profesion");
^
Use the jQuery function .data() to get data attributes.
Look at this code snippet using the .each to loop over all elements returned by this selector .fc-event:
$('#filterByProfession').change(function() {
var filterVal = $(this).val();
$(".fc-event").hide().each(function() {
if ($(this).data("profesion") === filterVal) {
$(this).show();
}
});
});
Example with static data
$('#filterByProfession').change(function() {
var filterVal = $(this).val();
$(".fc-event").hide().each(function() {
if ($(this).data("profesion") === filterVal) {
$(this).show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='filterByProfession'>
<option>-----</option>
<option>Developer</option>
<option>Cloud computing</option>
</select>
<div id="user-append">
<div class="fc-event draggable-user" data-profesion="Developer" id="user_1" style="z-index: 9999;">
<div class="container-fluid">
<input type="hidden" value="1" id="user_1_value" class="userId">
<div class="row" style="justify-content: center;">
<div class="col-xs-3 avatar-col">
<div class="innerAvatarUserLeft">
<img src="'+getUserImage(user.avatar)+'" style="margin: 0 auto;">
</div>
</div>
<div class="col-xs-9 data-col">
Developer
<p class="fullName dataText">Ele</p>
<p class="usr_Gender dataText">Male</p>
<div style="position: relative">
<li class="availableUnavailable"></li>
<li class="usr_profesion dataText">AVAILABLE</li>
</div>
<p class="user_id" style="float:right;margin: 3px">11</p>
</div>
</div>
</div>
</div>
</div>
<div id="user-append">
<div class="fc-event draggable-user" data-profesion="Cloud computing" id="user_2" style="z-index: 9999;">
<div class="container-fluid">
<input type="hidden" value="2" id="user_2_value" class="userId">
<div class="row" style="justify-content: center;">
<div class="col-xs-3 avatar-col">
<div class="innerAvatarUserLeft">
<img src="'+getUserImage(user.avatar)+'" style="margin: 0 auto;">
</div>
</div>
<div class="col-xs-9 data-col">
Cloud computing
<p class="fullName dataText">Enri</p>
<p class="usr_Gender dataText">Male</p>
<div style="position: relative">
<li class="availableUnavailable"></li>
<li class="usr_profesion dataText">AVAILABLE</li>
</div>
<p class="user_id" style="float:right;margin: 3px">11</p>
</div>
</div>
</div>
</div>
</div>
See? the sections are being hidden according to the selected option.
Try using this
$(".fc-event[data-profesion='" + filterVal + "']").show();
$(".fc-event[data-profesion!='" + filterVal + "']").hide();

Wrap divs according to the bootstrap row conditions

I have following condition in which what i want is when my child div's first class col-md-4 and beneath div class's numeric digits 4+4+4 >= 12 then wrap those in div having class row.Fidle of my problem Fiddle
<div class="row questionsRows">
<div class="col-md-4 coulmnQuestions"></div>
<div class="col-md-4 coulmnQuestions"></div>
<div class="col-md-4 coulmnQuestions"></div>
<div class="col-md-4 coulmnQuestions"></div>
<div class="col-md-4 coulmnQuestions"></div>
</div>
now i want to wrap divs in a row when my count of inner div's class is 12.
like this
<div class="row questionsRows">
<div class="row">
<div class="col-md-4 coulmnQuestions"></div>
<div class="col-md-4 coulmnQuestions"></div>
<div class="col-md-4 coulmnQuestions"></div>
</div>
<div class="row">
<div class="col-md-4 coulmnQuestions"></div>
<div class="col-md-4 coulmnQuestions"></div>
</div>
</div>
Code i have tried :
function WrapRows() {
var RowComplete = 0;
var divs;
$('.questionsRows').children('.coulmnQuestions').each(function () {
debugger;
var classes = $(this).attr("class").split(" ");
var getFirstClass = classes[0];
var value = getFirstClass.slice(7);
RowComplete = RowComplete + value;
divs = $(this).add($(this).next());
if (RowComplete >= 12)
{
divs.wrapAll('<div class="row"></div>');
RowComplete = 0;
}
});
and its not giving desired result , its not adding first row .
<div class="row questionsRows">
<div class="col-md-4 coulmnQuestions"></div>
<div class="row">
<div class="col-md-4 coulmnQuestions"></div>
<div class="col-md-4 coulmnQuestions"></div>
</div>
</div>
I got it:
var RowComplete = 0;
var divs;
$('.questionsRows').children('.coulmnQuestions').each(function () {
var classes = $(this).attr("class").split(" ");
var getFirstClass = classes[0];
var value = parseInt(getFirstClass.slice(7));
if(RowComplete==0) {
divs = $(this);
} else {
divs = divs.add($(this))
}
RowComplete = RowComplete + value;
console.log(RowComplete)
if (RowComplete >= 12)
{
console.log(divs)
divs.wrapAll('<div class="wrapper"></div>');
RowComplete = 0;
}
});
My guess is that in this line:
divs = $(this).add($(this).next());
you are catching the next tag of <div class="col-md-4 coulmnQuestions"></div>, and you should get the same tag, I mean <div class="col-md-4 coulmnQuestions"></div> tag. So I'd do:
divs = $(this).add($(this));
Anyway, if you add the code at http://jsfiddle.net it would be easier to see for us.

drag and drop working funny when using variable draggables and droppables

i have some containers that contain some divs like:
<div id="container1">
<div id="task1" onMouseOver="DragDrop("+1+");"> </div>
<div id="task2" onMouseOver="DragDrop("+2+");"> </div>
<div id="task3" onMouseOver="DragDrop("+3+");"> </div>
<div id="task4" onMouseOver="DragDrop("+4+");"> </div>
</div>
<div id="container2">
<div id="task5" onMouseOver="DragDrop("+5+");"> </div>
<div id="task6" onMouseOver="DragDrop("+6+");"> </div>
</div>
<div id="container3">
<div id="task7" onMouseOver="DragDrop("+7+");"> </div>
<div id="task8" onMouseOver="DragDrop("+8+");"> </div>
<div id="task9" onMouseOver="DragDrop("+9+");"> </div>
<div id="task10" onMouseOver="DragDrop("+10+");"> </div>
</div>
i'm trying to drag tasks and drop them in one of the container divs, then reposition the dropped task so that it doesn't affect the other divs nor fall outside one of them
and to do that i'm using the event onMouseOver to call the following function:
function DragDrop(id) {
$("#task" + id).draggable({ revert: 'invalid' });
for (var i = 0; i < nameList.length; i++) {
$("#" + nameList[i]).droppable({
drop: function (ev, ui) {
var pos = $("#task" + id).position();
if (pos.left <= 0) {
$("#task" + id).css("left", "5px");
}
else {
var day = parseInt(parseInt(pos.left) / 42);
var leftPos = (day * 42) + 5;
$("#task" + id).css("left", "" + leftPos + "px");
}
}
});
}
}
where:
nameList = [container1, container2, container3];
the drag is working fine, but the drop is not really, it's just a mess!
any help please??
when i hardcode the id and the container, then it works beautifully, but as soon as i use id in drop then it begins to work funny!
any suggestions???
thanks a million in advance
Lina
Consider coding it like this:
<div id="container1" class="container">
<div id="task1" class="task">1 </div>
<div id="task2" class="task">2 </div>
<div id="task3" class="task">3 </div>
<div id="task4" class="task">4 </div>
</div>
<div id="container2" class="container">
<div id="task5" class="task">5 </div>
<div id="task6" class="task">6 </div>
</div>
<div id="container3" class="container">
<div id="task7" class="task">7 </div>
<div id="task8" class="task">8 </div>
<div id="task9" class="task">9 </div>
<div id="task10" class="task">10 </div>
</div>
$(function(){
$(".task").draggable({ revert: 'invalid' });
$(".container").droppable({
drop: function (ev, ui) {
//process dropped item
}
});
})

Categories