Can someone help me write this in javascript - javascript

I am trying to write this code in javascript from jquery
I already tried but cant seems to get equivalent to work.
$(document).ready(function() {
$('a').click(function() {
var selected = $(this);
$('a').removeClass('active');
$(selected).addClass('active');
});
var $a = $('.a'),
$b = $('.b'),
$c = $('.c'),
$d = $('.d'),
$home = $('.home'),
$about = $('.about');
$a.click(function() {
$home.fadeIn();
$about.fadeOut();
});
$b.click(function() {
$home.fadeOut();
$about.fadeIn();
});
});
The code works perfect in jQuery, but am trying to just use javascript. Its basically to add and remove class when a nav item is selected. I don't know if am explaining as clear as possible but am try to write the equivalent of this in javascript.
This is what I have tried.
var callback = function(){
var clickHandler1 = function() {
document.getElementById("home").classList.remove("home");
//var rem = document.getElementById("home");
//fadeOut(rem);
//alert("I am clicked B");
};
var anchors1 = document.getElementsByClassName("b");
for (var i = 0; i < anchors1.length; i++) {
var current = anchors1[i];
current.addEventListener('click', clickHandler1, false);
}
function fadeOut(el){
el.style.opacity = 1;
function fade() {
if ((el.style.opacity -= .1) < 0) {
el.style.display = "none";
} else {
requestAnimationFrame(fade);
}
})();
};
fadeIn(el, display){
el.style.opacity = 0;
el.style.display = display || "block";
(function fade() {
var val = parseFloat(el.style.opacity);
if (!((val += .1) > 1)) {
el.style.opacity = val;
requestAnimationFrame(fade);
}
})();
};
}
if ( document.readyState === "complete" || (document.readyState !== "loading" && !document.documentElement.doScroll)) {
callback();
} else {
document.addEventListener("DOMContentLoaded", callback);
}

The code in es6:
window.onload = function() {
const allLinks = document.querySelectorAll('a')
console.log(allLinks)
const removeAllClass = () => {
allLinks.forEach(link => {
link.classList.remove('active')
})
}
allLinks.forEach(element => {
element.addEventListener('click', event => {
removeAllClass()
element.classList.add('active')
})
})
let $a = document.querySelectorAll('.a'),
$b = document.querySelectorAll('.b'),
$home = document.querySelector('.home'),
$about = document.querySelector('.about');
$a.forEach(element => {
element.addEventListener('click', event => {
$about.classList.remove('fadeIn');
$home.classList.add('fadeIn');
})
})
$b.forEach(element => {
element.addEventListener('click', event => {
$home.classList.remove('fadeIn');
$about.classList.add('fadeIn');
})
})
}
you can see working on https://codepen.io/rwladyka/pen/qBBBpvy

document.getElementsByClassName('a') is the javascript equivalent of $('.a')

Related

Improve my Jquery code to hide and show elements

I am new to Jquery and learning. I wrote some script, but I know its not efficient. Trying to follow DRY principles. Can someone please make this look nicer...it works fine, but i dont like it.
It works, just not efficient code.
<script>
$(document).ready(function () {
var val = $('#id_ocftype').val();
if (val <= 3) {
$('#div_id_date').hide();
$('#div_id_amount').hide();
$('#div_id_signedby').hide();
}
else {
$('#div_id_date').show();
$('#div_id_amount').show();
$('#div_id_signedby').show();
};
$('#id_ocftype').change(function () {
var val = $(this).val();
if (val <= 3) {
$('#div_id_date').hide();
$('#div_id_amount').hide();
$('#div_id_signedby').hide();
}
else {
$('#div_id_date').show();
$('#div_id_amount').show();
$('#div_id_signedby').show();
};
});
});
</script>
Since the conditional statement inside the jquery code is same. You can wrap it into single javascript function and call it whereever it is needed.
<script>
$(document).ready(function () {
const showAndHide = (val) => {
if (val <= 3) {
$('#div_id_date').hide();
$('#div_id_amount').hide();
$('#div_id_signedby').hide();
}
else {
$('#div_id_date').show();
$('#div_id_amount').show();
$('#div_id_signedby').show();
};
}
var val = $('#id_ocftype').val();
showAndHide(val);
$('#id_ocftype').change(function () {
var val = $(this).val();
showAndHide(val);
});
});
</script>
The elements to show or hide are always the same, so you can put them all into a single variable and reference that variable.
$(document).ready(function () {
const elms = $('#div_id_date, #div_id_amount, #div_id_signedby');
const onChange = () => {
const val = $('#id_ocftype').val();
if (val <= 3) {
elms.hide();
} else {
elms.show();
};
};
onChange();
$('#id_ocftype').change(onChange);
});
You can look into .toggleClass.
It allows you to specify when to add/ remove class.
function handleVisibility() {
var val = $('#id_ocftype').val();
const hide = val <= 3
$('#div_id_date').toggleClass('hide', hide)
$('#div_id_amount').toggleClass('hide', hide)
$('#div_id_signedby').toggleClass('hide', hide)
}
$(document).ready(function() {
$('#id_ocftype').change(handleVivibility);
handleVisibility()
});
you can create a common function
<script>
$(document).ready(function () {
var val = $('#id_ocftype').val();
const hideEl = () => {
$('#div_id_date').hide();
$('#div_id_amount').hide();
$('#div_id_signedby').hide();
}
const showEl = () => {
$('#div_id_date').show();
$('#div_id_amount').show();
$('#div_id_signedby').show();
}
if (val <= 3) {
hideEl();
}
else {
showEl();
};
$('#id_ocftype').change(function () {
var val = $(this).val();
if (val <= 3) {
hideEl();
}
else {
showEl();
};
});
});
</script>
also you can use toggle
$("button").click(() => {
$("#test").toggle();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">test</div>
<button>Hide/Show</button>

I have two independently working functions - I cannot get them to work together

I have two independent functions one to build a carousel and one to detect swipe Left or Right.
I cannot seem to find a way to use the function which navigates through the carousel into my Swipe Left or Right function (or vice versa).
I am at the end of my JS coding limits and struggling.
Here is the except:
this.doSomething = (event) => {
if (this.whatGestureDirection() == 'L') {
hpCarousel.move(-1);
} else {
hpCarousel.move(1);
}
}
I have tried alternatives; having google'd around there is a bind method. However, this is a bust too.
this.doSomething = (event) => {
if (this.whatGestureDirection() == 'L') {
let bindTheFunc;
bindTheFunc.bind(hpCarousel.move(-1));
return bindTheFunc;
} else {
let bindTheFunc;
bindTheFunc.bind(hpCarousel.move(1));
return bindTheFunc;
}
}
window.addEventListener('load', () => {
const hpCarousel = new carousel('area', 1);
const hpCarouselSwipe = new getSwipeX({elementId: 'homepage_carousel_wrapper'});
})
function getSwipeX({elementId}) {
this.e = document.getElementsByClassName(elementId)[0];
this.initialPosition = 0;
this.lastPosition = 0;
this.getTouchStart = (event) => {
event.preventDefault();
if (window.PointerEvent) {
this.e.setPointerCapture(event.pointerId);
}
return this.initalTouchPos = this.getGesturePoint(event);
}
this.getTouchMove = (event) => {
event.preventDefault();
return this.lastPosition = this.getGesturePoint(event);
}
this.getTouchEnd = (event) => {
event.preventDefault();
if (window.PointerEvent) {
this.e.releasePointerCapture(event.pointerId);
}
this.doSomething();
this.initialPosition = 0;
}
this.getGesturePoint = (event) => {
this.point = event.pageX
return this.point;
}
this.whatGestureDirection = (event) => {
const diffInPosition = this.initalTouchPos - this.lastPosition;
return (Math.sign(diffInPosition) > 0 ) ? `L` : `R`;
}
this.doSomething = (event) => {
if (this.whatGestureDirection() == 'L') {
**hpCarousel.move(-1);**
} else {
**hpCarousel.move(1);**
}
}
if (window.PointerEvent) {
this.e.addEventListener('pointerdown', this.getTouchStart, true);
this.e.addEventListener('pointermove', this.getTouchMove, true);
this.e.addEventListener('pointerup', this.getTouchEnd, true);
this.e.addEventListener('pointercancel', this.getTouchEnd, true);
}
}
I have a carousel script which a SO user kindly helped me with last week. It works great.
function carousel(id, index) {
this.slideIndex = index;
let carousel = document.getElementById(id);
this.slides = [...document.getElementsByClassName('homepage_carousel')];
let prev = carousel.getElementsByClassName('prev')[0];
let next = carousel.getElementsByClassName('next')[0];
prev.addEventListener('click', () => {
this.move(-1);
});
next.addEventListener('click', () => {
this.move(1);
});
this.hideAll = () => {
this.slides.forEach((slide) => {
slide.style.display = 'none';
});
};
this.show = () => {
this.hideAll();
this.slides[this.slideIndex - 1].style.display = 'flex';
}
this.move = (amount) => {
this.slideIndex += amount;
this.slideIndex = (this.slideIndex > this.slides.length) ? 1 : (this.slideIndex < 1) ? this.slides.length : this.slideIndex;
this.show();
}
this.show();
}
you can pass hpCarousel into hpCarouselSwipe as an argument.
window.addEventListener('load', () => {
const hpCarousel = new carousel('area', 1);
const hpCarouselSwipe = new getSwipeX({elementId: 'homepage_carousel_wrapper', carousel:hpCarousel});
})
function getSwipeX({elementId,carousel}) {
...
this.hpCarousel = carousel
}
And then later:
this.doSomething = (event) => {
if (this.whatGestureDirection() == 'L') {
this.hpCarousel.move(-1);
} else {
this.hpCarousel.move(1);
}
}
I did not test it, but it should work. You can pass a function into another function.

Javascript: Detecting a long press

In order to differentiate between scroll and drag&drop on touch devices I decided to consider that drag event occurred if it follows long press.
Is there a way to make code below cleaner?
const listItem = document.getElementById("listItem");
listItem.addEventListener("touchstart", onTouchstart);
listItem.addEventListener("touchmove", onTouchmove);
listItem.addEventListener("touchend", onTouchend);
const longpress = false;
const longpressStart = 0;
const longpressChecked = false;
const LONGPRESS_DURATION = 100;
function onTouchstart() {
longpress = false;
longpressStart = Date.now();
}
function isLongPress() {
if (longpressChecked) {
return longpress;
}
if (Date.now() - longpressStart >= LONGPRESS_DURATION) {
longpress = true;
}
longpressChecked = true;
return longpress;
}
function onTouchmove() {
if (isLongPress()) {
// drag and drop logic
}
}
function onTouchend() {
longpress = false;
longpressStart = 0;
longpressChecked = false;
}
Thank you for help
You could beautify this through using some curried arrow functions:
const listen = (el, name) => handler => el.addEventListener(name, handler);
const since = (onStart, onEnd) => {
let last = 0;
onStart(() => last = Date.now());
onEnd(() => last = 0);
return time => Date.now() - last < time;
};
So you can just do:
const longPress = since(
listen(listItem, "touchstart"),
listen(listItem, "touchend")
);
listen(listItem, "touchmove")(evt => {
if(longPress(100)) {
//...
}
});
const listItem = document.getElementById("listItem");
listItem.addEventListener("touchstart", onTouchstart);
listItem.addEventListener("touchmove", onTouchmove);
listItem.addEventListener("touchend", onTouchend);
var onlongtouch = false;
function onTouchstart() {
timer = setTimeout(function() {
onlongtouch = true;
}, 100);
}
function onTouchmove() {
if(onlongtouch) {
// do something
}
}
function onTouchend() {
if (timer)
clearTimeout(timer);
onlongtouch = false;
}

jquery conflict with js script

welcome all ,
i have a problem with my images slider , it runs successfuly until poll script excuted then it stops , tried to combine both scripts didn't work also tried to use noConflict but in stops both of them .
this is the slider
(function ($) {
$.fn.s3Slider = function (vars) {
var element = this;
var timeOut = (vars.timeOut != undefined) ? vars.timeOut : 4000;
var current = null;
var timeOutFn = null;
var faderStat = true;
var mOver = false;
var items = $("#sliderContent .sliderImage");
var itemsSpan = $("#sliderContent .sliderImage span");
items.each(function (i) {
$(items[i]).mouseover(function () {
mOver = true
});
$(items[i]).mouseout(function () {
mOver = false;
fadeElement(true)
})
});
var fadeElement = function (isMouseOut) {
var thisTimeOut = (isMouseOut) ? (timeOut / 2) : timeOut;
thisTimeOut = (faderStat) ? 10 : thisTimeOut;
if (items.length > 0) {
timeOutFn = setTimeout(makeSlider, thisTimeOut)
} else {
console.log("Poof..")
}
};
var makeSlider = function () {
current = (current != null) ? current : items[(items.length - 1)];
var currNo = jQuery.inArray(current, items) + 1;
currNo = (currNo == items.length) ? 0 : (currNo - 1);
var newMargin = $(element).width() * currNo;
if (faderStat == true) {
if (!mOver) {
$(items[currNo]).fadeIn((timeOut / 6), function () {
if ($(itemsSpan[currNo]).css("bottom") == 0) {
$(itemsSpan[currNo]).slideUp((timeOut / 6), function () {
faderStat = false;
current = items[currNo];
if (!mOver) {
fadeElement(false)
}
})
} else {
$(itemsSpan[currNo]).slideDown((timeOut / 6), function () {
faderStat = false;
current = items[currNo];
if (!mOver) {
fadeElement(false)
}
})
}
})
}
} else {
if (!mOver) {
if ($(itemsSpan[currNo]).css("bottom") == 0) {
$(itemsSpan[currNo]).slideDown((timeOut / 6), function () {
$(items[currNo]).fadeOut((timeOut / 6), function () {
faderStat = true;
current = items[(currNo + 1)];
if (!mOver) {
fadeElement(false)
}
})
})
} else {
$(itemsSpan[currNo]).slideUp((timeOut / 6), function () {
$(items[currNo]).fadeOut((timeOut / 6), function () {
faderStat = true;
current = items[(currNo + 1)];
if (!mOver) {
fadeElement(false)
}
})
})
}
}
}
};
makeSlider()
}
})(jQuery);
and this is the poll script
window.onload = function() {
$(".sidePollCon").load("ar_poll.html", function(r, s, xhr) {
if (s == "error") {
$(".sidePollCon").load("poll.html");
} else {
$(".vote_booroo").html("صوت الان");
$(".viewresults").html("شاهد النتيجة");
$("fieldset p").html("");
$(".results_booroo p").html("");
$(".result_booroo").attr("src", "../images/poll_color.jpg");
}
});
};
One potential problem could be the window.onload assignment. It is very prone to conflict.
Every time you do window.onload = the previous assignemnt will be overridden. See demo here:
The output shows that the first window.onload assignment never gets called, while the jQuery alternative does get called.
jQuery.noConflict does little in this regard. All it does is to prevent override the $ symbol so that another lib can use it.
So if you are also using the window.onload event to invoke the slider, then you have conflict. You can easily solve this problem by using the jquery format:
$(window).load(function() {
...
});
However usually you would tie the event to $(document).load(function(){...}); or in short form: $(function(){...}).
So for your poll that would be:
$(function(){
$(".sidePollCon").load("ar_poll.html", function(r, s, xhr) {
if (s == "error") {
$(".sidePollCon").load("poll.html");
} else {
$(".vote_booroo").html("صوت الان");
$(".viewresults").html("شاهد النتيجة");
$("fieldset p").html("");
$(".results_booroo p").html("");
$(".result_booroo").attr("src", "../images/poll_color.jpg");
}
});
});
Hope that helps.
resolving conflicts in jquery (possibly with another JS library .. like script.aculo.us) can be resolved using noconflict()
http://api.jquery.com/jQuery.noConflict/
$.noConflict();
but make sure that u have no error in your javascript code itself. use firebug and
console.log('') to test your script.

Javascript's Callback Function

I am using Lazy Load Jquery plugin here on my test page: http://bloghutsbeta.blogspot.com/2012/03/testing-2_04.html
And this is the minified script for lazyload:
Code:
<script src="http://files.cryoffalcon.com/javascript/jquery.lazyload.min.js" type="text/javascript" charset="utf-8"></script>
this one is to trigger lazy load:
Code:
<script type="text/javascript" charset="utf-8">
$(function() {
$("img").lazyload({
effect : "fadeIn"
});
});
</script>
In the above script I have added fadeIn effect to it, I don't know if I have done it right according to script writting I am not good in scripts ^^ So, I would like have an advise if it's well written or there is some comma mistake.
But that is not my important question, all of the above lazy load plugin is used with QuickSand Jquery plugin that I am using for sorting.
QuickSand Jquery Plugin requires callback function if it's tooltip or Lazy Load, So can someone kindly tell me how to make lazy load work together with quicksand jquery.
Here is the quicksand's script:
Code:
<script type="text/javascript">
(function(cash) {
$.fn.sorted = function(customOptions) {
var options = {
reversed: false,
by: function(a) {
return a.text();
}
};
$.extend(options, customOptions);
$data = $(this);
arr = $data.get();
arr.sort(function(a, b) {
var valA = options.by($(a));
var valB = options.by($(b));
if (options.reversed) {
return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;
} else {
return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;
}
});
return $(arr);
};
})(jQuery);
$(function() {
var read_button = function(class_names) {
var r = {
selected: false,
type: 0
};
for (var i=0; i < class_names.length; i++) {
if (class_names[i].indexOf('selected-') == 0) {
r.selected = true;
}
if (class_names[i].indexOf('segment-') == 0) {
r.segment = class_names[i].split('-')[1];
}
};
return r;
};
var determine_sort = function($buttons) {
var $selected = $buttons.parent().filter('[class*="selected-"]');
return $selected.find('a').attr('data-value');
};
var determine_kind = function($buttons) {
var $selected = $buttons.parent().filter('[class*="selected-"]');
return $selected.find('a').attr('data-value');
};
var $preferences = {
duration: 800,
easing: 'easeInOutQuad',
adjustHeight: 'dynamic'
};
var $list = $('#data');
var $data = $list.clone();
var $controls = $('ul#gamecategories ul');
$controls.each(function(i) {
var $control = $(this);
var $buttons = $control.find('a');
$buttons.bind('click', function(e) {
var $button = $(this);
var $button_container = $button.parent();
var button_properties = read_button($button_container.attr('class').split(' '));
var selected = button_properties.selected;
var button_segment = button_properties.segment;
if (!selected) {
$buttons.parent().removeClass('selected-0').removeClass('selected-1').removeClass('selected-2');
$button_container.addClass('selected-' + button_segment);
var sorting_type = determine_sort($controls.eq(1).find('a'));
var sorting_kind = determine_kind($controls.eq(0).find('a'));
if (sorting_kind == 'all') {
var $filtered_data = $data.find('li');
} else {
var $filtered_data = $data.find('li.' + sorting_kind);
}
if (sorting_type == 'size') {
var $sorted_data = $filtered_data.sorted({
by: function(v) {
return parseFloat($(v).find('span').text());
}
});
} else {
var $sorted_data = $filtered_data.sorted({
by: function(v) {
return $(v).find('strong').text().toLowerCase();
}
});
}
$list.quicksand($sorted_data, $preferences, function () { $(this).tooltip (); } );
}
e.preventDefault();
});
});
var high_performance = true;
var $performance_container = $('#performance-toggle');
var $original_html = $performance_container.html();
$performance_container.find('a').live('click', function(e) {
if (high_performance) {
$preferences.useScaling = false;
$performance_container.html('CSS3 scaling turned off. Try the demo again. <a href="#toggle">Reverse</a>.');
high_performance = false;
} else {
$preferences.useScaling = true;
$performance_container.html($original_html);
high_performance = true;
}
e.preventDefault();
});
});
</script>
you can use this:
$list.quicksand($sorted_data, $preferences, function(){
$(this).tooltip ();
$("img").lazyload({
effect : "fadeIn"
});
});

Categories