JS Slider doesnt work - javascript

I have a js class for slider, but something went wrong when connecting js to html, i have class for slider, slider container, arrows and dots .
Please help me
<div class="b-slider">
<ul class="slider js-slides">
<li class="slide-one js-slide"></li>
<li class="slide-two js-slide"></li>
<li class="slide-three js-slide"></li>
</ul>
<ul class="dots">
<li class="dot js-bull"><a class="show-slider"></a></li>
<li class="dot js-bull active"><a class="show-slider"></a></li>
<li class="dot js-bull"><a class="show-slider"></a></li>
</ul>

and sliders class via JS
class Slider {
constructor (root, options = {}) {
var defaultOptions = {};
this.root = root;
this.options = _.assign(defaultOptions, options);
this.itemsCount = 0;
this.itemWidth = 0;
this.currentIndex = 0;
this._cacheNodes();
this._initialize();
this._bindEvents();
}
_cacheNodes () {
this.nodes = {
slidesContainer: this.root.find('.js-slides'),
slides: this.root.find('.js-slide'),
left: this.root.find('.js-left'),
right: this.root.find('.js-right'),
bulls: this.root.find('.js-bull')
};
}
_initialize () {
this.itemsCount = this.nodes.slides.length;
this.itemWidth = this.nodes.slides.eq(0).outerWidth(true);
this.nodes.slidesContainer.width(this.itemWidth * (this.itemsCount));
this._goTo(this.currentIndex);
}
_bindEvents () {
$$.window.on('resize', () => {
this._initialize();
});
this.nodes.left.on('click', () => {
this._goTo(this.currentIndex - this.OnScreenCount);
});
this.nodes.right.on('click', () => {
this._goTo(this.currentIndex + this.OnScreenCount);
});
if (this.nodes.bulls.length) {
this.nodes.bulls.on('click', (event) => {
this._goTo($(event.currentTarget).index());
});
}
}
_goTo (index) {
if (index <= 0) {
this.nodes.left.addClass('disabled');
} else {
this.nodes.left.removeClass('disabled');
}
if (index > this.itemsCount - 1 - this.screenCount) {
this.nodes.right.addClass('disabled');
} else {
this.nodes.right.removeClass('disabled');
}
if ((index > this.itemsCount - this.screenCount) || (index < 0)) {
return;
}
this.nodes.slidesContainer.css({
transform: `translateX(${ -index * this.itemWidth }px)`
});
if (this.nodes.bulls.length) {
this.nodes.bulls.eq(this.currentIndex).removeClass('active');
}
this.currentIndex = index;
if (this.nodes.bulls.length) {
this.nodes.bulls.eq(this.currentIndex).addClass('active');
}
}

Related

Error on Sortting Items is not a function

I have a problem with my code
So, there is picture with like, when i click on the heart that add a like
there is a container down ma page and then the likes are also displayed in it.
(picture to show you a context)
The problem is everything work fine, but when you use my function "filter"
the likes are working on the photos but not down the page and that return me an error i don't really understand from where that come.
So can you help me please ?
import showMethods from "../factories/showMethods.js";
import lightbox from "../factories/lightbox.js";
import formularSecur from "../factories/formularSecur.js";
export default class OnePhotographer {
constructor() {
this.photographer = null;
this.medias = [];
this.likes = 0;
this.lightbox = lightbox;
this.indexLightbox = 0;
this.getPhotographer();
this.eInit();
}
eInit() {
document.getElementById("filtre").addEventListener("change", (e) => {
this.filter(e.target.value);
});
document.getElementById("filtre").addEventListener("click", (e) => {
this.filter(e.target.value);
});
document.getElementById("contactForm").addEventListener("submit", (e) => {
e.preventDefault();
formularSecur.checkForm(this);
document.getElementById("contactForm").reset();
});
this.lightbox.init(this);
document.getElementById("closeLightbox").addEventListener("click", () => {
this.lightbox.closeLightbox();
});
document.getElementById("prevBox").addEventListener("click", () => {
this.lightbox.navLightbox("prev");
});
document.getElementById("nextBox").addEventListener("click", () => {
this.lightbox.navLightbox("next");
});
document.addEventListener("keydown", (event) => {
if (event.code == "ArrowLeft") {
this.lightbox.navLightbox("prev");
} else if (event.code == "ArrowRight") {
this.lightbox.navLightbox("next");
} else if (event.code == "Escape") {
this.lightbox.closeLightbox();
}
});
}
filter(param) {
if (param === "popular") {
this.medias = this.medias.sort(this.order(param));
} else {
this.medias = this.medias.sort(this.order(param)).reverse();
}
document.querySelector(".containerMedias").innerHTML = "";
this.medias.forEach((media, index) => {
showMethods.showMedia(media, index);
showMethods.showLikes(this, instance);
});
}
order(settings) {
return function (x, y) {
if (x[settings] < y[settings]) {
return -1;
}
if (x[settings] > y[settings]) {
return 1;
}
return 0;
};
}
setMedias(media) {
this.medias = media;
}
async getPhotographer() {
const response = await fetch("./data/photographers.json");
const res = await response.json();
const id = this.idUrlCatch();
res.photographers.forEach((photographer) => {
if (photographer.id == id) {
this.photographer = photographer;
res.media.forEach((media) => {
if (media.photographerId == this.photographer.id) {
this.medias.push(media);
this.likes += media.likes;
}
});
this.medias = this.medias.sort(this.order("popular"));
}
});
showMethods.showData(this);
showMethods.showLikes(this, instance);
}
idUrlCatch() {
const str = window.location.href;
const url = new URL(str);
if (url.searchParams.get("id")) {
const id = url.searchParams.get("id");
return id;
}
}
showData() {
showMethods.showData(this);
showMethods.showLikes(this, instance);
}
showHeader() {
showMethods.showHeader(this);
}
showMedia(media, index) {
showMethods.showMedia(media, index, this);
}
showLikes() {
showMethods.showLikes(this, instance);
}
setSrcLightbox() {
showMethods.setSrcLightbox(this);
}
closeLightbox() {
showMethods.closeLightbox(this);
}
navLightbox() {
}
}
this is the second part of my code
import lightbox from "../factories/lightbox.js";
export default {
showData: function (instance) {
this.showHeader(instance);
instance.medias.forEach((media, index) => {
this.showMedia(media, index, instance);
});
instance.showLikes();
},
showHeader: function (instance) {
const infoHeader = document.querySelector(".photograph-header .containerInfo");
const title = document.createElement("h1");
title.textContent = instance.photographer.name;
const loc = document.createElement("h3");
loc.textContent = `${instance.photographer.city}, ${instance.photographer.country}`;
const tagline = document.createElement("span");
tagline.textContent = instance.photographer.tagline;
infoHeader.appendChild(title);
infoHeader.appendChild(loc);
const headerImg = document.querySelector(
".photograph-header .containerImg"
);
const pic = `assets/photographers/${instance.photographer.portrait}`;
const img = document.createElement("img");
img.setAttribute("src", pic);
img.setAttribute("alt", instance.photographer.name);
headerImg.appendChild(img);
},
showMedia: function (media, index, instance) {
const mediaSection = document.querySelector(".containerMedias");
const card = document.createElement("div");
card.classList.add("cardMedia");
const containerImg = document.createElement("div");
containerImg.classList.add("containerImg");
if (media.image) {
const mediaUrl = `assets/medias/${media.image}`;
const mediaItem = document.createElement("img");
mediaItem.dataset.index = index;
mediaItem.setAttribute("tabindex", 0);
mediaItem.addEventListener("click", (e) => {
lightbox.showLightbox(e, instance);
});
mediaItem.addEventListener("focus", () => {
mediaItem.addEventListener("keydown", (e) => {
if (e.code == "Enter") {
lightbox.showLightbox(e, instance);
}
});
});
mediaItem.setAttribute("src", mediaUrl);
mediaItem.setAttribute("alt", media.title);
containerImg.appendChild(mediaItem);
} else {
const mediaUrl = `assets/medias/${media.video}`;
const mediaItem = document.createElement("video");
mediaItem.dataset.index = index;
mediaItem.controls = true;
mediaItem.classList.add("media");
mediaItem.addEventListener("click", (e) => {
lightbox.showLightbox(e, instance);
});
mediaItem.setAttribute("src", mediaUrl);
mediaItem.setAttribute("alt", media.title);
mediaItem.setAttribute("data-index", index);
containerImg.appendChild(mediaItem);
}
const subContain = document.createElement("div");
subContain.classList.add("subContain");
const picTitle = document.createElement("h3");
picTitle.textContent = media.title;
const like = document.createElement("span");
like.setAttribute("tabindex", 0);
like.classList.add("like");
like.innerHTML = `${media.likes} <i class="fa-regular fa-heart"></i>`;
like.addEventListener("click", () => {
like.classList.toggle("active");
if (like.classList.contains("active")) {
media.likes += 1;
instance.likes += 1;
like.innerHTML = `${media.likes} <i class="fa-solid fa-heart"></i>`;
} else {
media.likes -= 1;
instance.likes -= 1;
like.innerHTML = `${media.likes} <i class="fa-regular fa-heart"></i>`;
}
instance.showLikes();
});
like.addEventListener("focus", () => {
like.addEventListener("keydown", (event) => {
if (event.code == "Enter") {
like.classList.toggle("active");
if (like.classList.contains("active")) {
media.likes += 1;
instance.likes += 1;
like.innerHTML = `${media.likes} <i class="fa-solid fa-heart"></i>`;
} else {
media.likes -= 1;
instance.likes -= 1;
like.innerHTML = `${media.likes} <i class="fa-regular fa-heart"></i>`;
}
instance.showLikes();
}
});
});
subContain.appendChild(picTitle);
subContain.appendChild(like);
card.appendChild(containerImg);
card.appendChild(subContain);
mediaSection.appendChild(card);
},
showLikes: function (instance) {
const priceContainer = document.createElement("div");
priceContainer.classList.add("priceContainer");
const likes = document.createElement("span");
likes.classList.add("likes");
likes.innerHTML = `<i class="fa-solid fa-heart"></i> ${instance.likes}`;
const priceDay = document.createElement("span");
priceDay.classList.add("priceDay");
priceDay.innerHTML = `<i class="fa-solid fa-dollar-sign"></i> ${instance.photographer.price}`;
priceContainer.appendChild(likes);
priceContainer.appendChild(priceDay);
document.querySelector(".photograph-header").appendChild(priceContainer);
},
};
i don't really get why with my function showMedia everithing is fine, but with showLikes not
the code error
Uncaught TypeError: instance.showLikes is not a function
at HTMLSpanElement.<anonymous> (showMethods.js:101:16)
(anonyme) # showMethods.js:101
if you help me that will save my life
Thank you for your time <3
So i find why the bug is happening when i use my "filter" Function.
I lose Instance on "showLikes" Function, so i don't have accès to the current instance.
One of my solution make my code in the onePhotograph.js, so no Instance ==> No bug.
I know this is maybe not the only solution, and maybe not the best. But this is a great solution also !
Best Regards

Tabs how can I add next and prev buttons?

Tabs how can I add next and prev buttons?
I'm have a tab component that needs the next and prev button as requirements.
I tried to build the component and now the extra bit is needed but I'm a bit stuck.
I'm not sure how to call the function and make it work within the existing one.
How do I add an extra click function for the buttons next and prev?
would be really useful to have it working. If anyone is able to put me on the right path, perhaps using a click even with some console.log in the right place?
class Tabs {
constructor() {
this.tabsBlocks = document.querySelectorAll(".tabs-block");
}
init() {
if (this.tabsBlocks.length > 0) {
Array.prototype.forEach.call(this.tabsBlocks, (tabBlock, index) => {
const tabContainer = tabBlock.querySelector(".tab-wrapper");
const tabs = tabBlock.querySelectorAll("button");
const panels = tabBlock.querySelectorAll(".panel");
const buttonNext = tabBlock.querySelector(".buttonNext");
const buttonPrev = tabBlock.querySelector(".buttonPrev");
tabContainer.setAttribute("role", "tablist");
Array.prototype.forEach.call(tabs, (tab) => {
if (tab.dataset.open === "true") this.toggleTabs(tab, panels);
tab.setAttribute("role", "tab");
tab.setAttribute(
"aria-controls",
`panel-${tab.dataset.target}-block-${index + 1}`
);
const associatedPanel = tabBlock.querySelector(
`[data-panel="${tab.dataset.target}"]`
);
if (associatedPanel !== null) {
associatedPanel.id = `panel-${tab.dataset.target}-block-${
index + 1
}`;
tab.id = `tab-${tab.dataset.target}-block-${index + 1}`;
}
tab.addEventListener("click", () => {
this.toggleTabs(tab, panels);
});
});
Array.prototype.forEach.call(panels, (panel) => {
const associatedTab = tabBlock.querySelector(
`[data-target="${panel.dataset.panel}"]`
);
panel.setAttribute("role", "tabpanel");
panel.setAttribute("aria-labelledby", `${associatedTab.id}`);
});
});
}
}
toggleTabs = (currentTab, panels, buttonNext, buttonPrev) => {
const tabs = currentTab.closest(".tabs-block").querySelectorAll("button");
const target = currentTab.dataset.target;
Array.prototype.forEach.call(tabs, (tab) => {
if (tab.dataset.target !== target) {
tab.classList.remove("is-active");
tab.setAttribute("aria-selected", "false");
}
});
Array.prototype.forEach.call(panels, (panel) => {
if (panel.dataset.panel !== target) {
panel.classList.remove("is-active");
} else {
panel.classList.add("is-active");
currentTab.classList.add("is-active");
currentTab.setAttribute("aria-selected", "true");
}
});
};
}
const components = {
Tabs: new Tabs()
};
components.Tabs.init();
.tabs-block .tab-wrapper li {
flex: 1 1 0%;
text-align: center;
}
.tabs-block .tab-wrapper li button {
font-weight: lighter;
font-size: 20px;
}
.tabs-block .tab-wrapper li button.is-active {
font-weight: normal;
}
.tabs-block .panel {
display: none;
}
.tabs-block .panel.is-active {
display: block;
}
<section class="tabs-block">
<ul class="tab-wrapper">
<li><button data-target="1" data-open="true">Tab title 1</button></li>
<li><button data-target="2">Tab title 2</button></li>
</ul>
<div class="panel-wrapper">
<div data-panel="1" class="panel">
<p>Panel 1 content</p>
</div>
<div data-panel="2" class="panel">
<p>Panel 2 content</p>
</div>
</div>
<button class="buttonNext"><< Prev</button>
<button class="buttonPrev">Next >></button>
</section>
This example works on codepen but does not in here.. Maybe babel preprozessor does something which i do not know...
Copy this to codepen and you will be happy.
class Pagination {
constructor(tabComponent, prevBtnId, nextBtnId) {
this.arrayUtils = new ArrayUtils()
this.tabComponent = tabComponent
this.prevBtn = document.getElementById(prevBtnId)
this.nextBtn = document.getElementById(nextBtnId)
// listen to tabComponents newly created Toggle event
// in which we wanna make sure to disable Btns or something..
this.tabComponent.onTabsToggle((tabs, tabIndex) => {
this.applyPaginationRules(tabs, tabIndex)
})
}
setDisabled(btn, value) {
if(value) {
btn.setAttribute('disabled', 'true')
} else {
btn.removeAttribute('disabled')
}
}
applyPaginationRules(tabs, newActiveIndex) {
const nextBtnDisabled = newActiveIndex === (tabs.length -1)
const prevBtnDisabled = newActiveIndex === 0
this.setDisabled(this.nextBtn, nextBtnDisabled)
this.setDisabled(this.prevBtn, prevBtnDisabled)
}
paginate(btn, action) {
const block = btn.closest('.tabs-block')
const panels = block.querySelectorAll('.panel')
const tabs = block.querySelectorAll('.tab-wrapper > li > button')
const activeIndex = Array.from(tabs)
.findIndex(t => t.getAttribute('data-open') === 'true')
if (tabs.length < 2) {
console.log('0 OR 1 tabs to toggle so no action.')
return
}
var newActiveIndex
if(action === 'next') {
newActiveIndex = this.arrayUtils.nextIndex(activeIndex, tabs)
}
else if(action === 'prev') {
newActiveIndex = this.arrayUtils.previousIndex(activeIndex, tabs)
}
else {
throw 'Invalid toggle action ' + action
}
// enable / disable next and previous btns..
this.applyPaginationRules(tabs, newActiveIndex)
this.tabComponent.toggleTabs(tabs[newActiveIndex], panels)
}
addPaginationListener(btn, action) {
btn.addEventListener('click', e => {
this.paginate(btn, action)
})
}
init() {
this.addPaginationListener(this.prevBtn, 'prev')
this.addPaginationListener(this.nextBtn, 'next')
// disable prev button on beggining since we start at 0..
this.setDisabled(this.prevBtn, true)
}
}
class ArrayUtils {
// getting next index in array
nextIndex(currentIndex, array) {
// if 0 OR 1 elements, index stays the same..
if(array.length < 2) return currentIndex
// if possible increment.
if(currentIndex < array.length -1) {
return currentIndex + 1
}
// if index would exceed array size go to start.
return 0
}
// getting previous INdex in array:
previousIndex(currentIndex, array) {
// if 0 OR 1 elements, index stays the same..
if(array.length < 2) return currentIndex
// if possible decrement!
if(currentIndex > 0) {
return currentIndex - 1
}
// start at the end of array when end is reached ofc.
return array.length -1
}
}
class Tabs {
constructor() {
this.tabsBlocks = document.querySelectorAll(".tabs-block");
this.onToggleHandlers = []
}
onTabsToggle(fn) {
this.onToggleHandlers.push(fn)
}
emitTabsToggle(tabs, tabIndex) {
this.onToggleHandlers.forEach(fn => fn(tabs, tabIndex))
}
init() {
if (this.tabsBlocks.length > 0) {
Array.prototype.forEach.call(this.tabsBlocks, (tabBlock, index) => {
const tabContainer = tabBlock.querySelector(".tab-wrapper");
const tabs = tabBlock.querySelectorAll(".tab-wrapper li button");
const panels = tabBlock.querySelectorAll(".panel");
tabContainer.setAttribute("role", "tablist");
Array.prototype.forEach.call(tabs, (tab, tabIndex) => {
if (tab.dataset.open === "true") this.toggleTabs(tab, panels);
tab.setAttribute("role", "tab");
tab.setAttribute(
"aria-controls",
`panel-${tab.dataset.target}-block-${index + 1}`
);
const associatedPanel = tabBlock.querySelector(
`[data-panel="${tab.dataset.target}"]`
);
if (associatedPanel !== null) {
associatedPanel.id = `panel-${tab.dataset.target}-block-${
index + 1
}`;
tab.id = `tab-${tab.dataset.target}-block-${index + 1}`;
}
tab.addEventListener("click", () => {
this.toggleTabs(tab, panels);
this.emitTabsToggle(tabs, tabIndex)
});
});
Array.prototype.forEach.call(panels, (panel) => {
const associatedTab = tabBlock.querySelector(
`[data-target="${panel.dataset.panel}"]`
);
panel.setAttribute("role", "tabpanel");
panel.setAttribute("aria-labelledby", `${associatedTab.id}`);
});
});
}
}
toggleTabs = (currentTab, panels) => {
const tabs = currentTab.closest(".tabs-block").querySelectorAll("button");
const target = currentTab.dataset.target;
Array.prototype.forEach.call(tabs, (tab) => {
if (tab.dataset.target !== target) {
tab.classList.remove("is-active");
tab.setAttribute('data-open', 'false')
tab.setAttribute("aria-selected", "false");
}
});
Array.prototype.forEach.call(panels, (panel) => {
if (panel.dataset.panel !== target) {
panel.classList.remove("is-active");
} else {
panel.classList.add("is-active");
}
});
/// activate tab..
currentTab.classList.add("is-active");
currentTab.setAttribute("data-open", 'true');
currentTab.setAttribute("aria-selected", "true");
};
}
const components = {
Tabs: new Tabs()
};
components.Tabs.init();
// have the pagination more decoupled from tabs!
// it uses tabs component but you can remove it OR apply it to other
// classes like so more easily..
const prevBtnId = 'pagination-prev'
const nextBtnId = 'pagination-next'
const pagination = new Pagination(components.Tabs, prevBtnId, nextBtnId)
pagination.init()
.tabs-block .tab-wrapper li {
flex: 1 1 0%;
text-align: center;
}
.tabs-block .tab-wrapper li button {
font-weight: lighter;
font-size: rem(20px);
}
.tabs-block .tab-wrapper li button.is-active {
font-weight: normal;
}
.tabs-block .panel {
display: none;
}
.tabs-block .panel.is-active {
display: block;
}
<section class="tabs-block">
<ul class="tab-wrapper">
<li><button data-target="1" data-open="true">Tab title 1</button></li>
<li><button data-target="2">Tab title 2</button></li>
<li><button data-target="3">Tab title 3</button></li>
<li><button data-target="4">Tab title 4</button></li>
</ul>
<div class="panel-wrapper">
<div data-panel="1" class="panel">
<p>Panel 1 content</p>
</div>
<div data-panel="2" class="panel">
<p>Panel 2 content</p>
</div>
<div data-panel="3" class="panel">
<p>Panel 3 content</p>
</div>
<div data-panel="4" class="panel">
<p>Panel 4 content</p>
</div>
</div>
<button class="buttonPrev" id="pagination-prev"><< Prev</button>
<button class="buttonNext" id="pagination-next">Next >></button>
</section>
You have to add eventListener to your button elements
buttonNext.addEventListener("click", myFunction);
buttonPrev.addEventListener("click", myFunction);
function myFunction() {
console.log("next")
}
Here are your Button Elements
<button id="nextBtn" class="buttonNext"><< Prev</button>
<button id="prevBtn" class="buttonPrev">Next >></button>
You have to get elements directly from DOM. use a unique class name or id for this purpose
const buttonNext = document.querySelector("#nextBtn");
const buttonPrev = document.querySelector("#prevBtn");
Now if the buttonNext and buttonPrev variables have the elements you can add eventListener. The event listener is of type click so whenever user clicks on any button the respective function will be called
buttonNext && buttonNext.addEventListener("click", handleNext);
buttonPrev && buttonPrev.addEventListener("click", handlePrev);
const handleNext = () => {
console.log("next")
}
const handlePrev = () => {
console.log("next")
}
I hope this will work for you. You can add any logic on next and prev buttons in respective functions
Working codepen demo
class Tabs {
constructor() {
this.tabsBlocks = document.querySelectorAll(".tabs-block");
}
init() {
if (this.tabsBlocks.length > 0) {
Array.prototype.forEach.call(this.tabsBlocks, (tabBlock, index) => {
const tabContainer = tabBlock.querySelector(".tab-wrapper");
const tabs = tabBlock.querySelectorAll("button");
const panels = tabBlock.querySelectorAll(".panel");
const Navigate= () => {
const buttonNext = document.querySelector("#nextBtn");
const buttonPrev = document.querySelector("#prevBtn");
const handleNext = () => {
console.log("next");
};
const handlePrev = () => {
console.log("prev");
};
buttonNext && buttonNext.addEventListener("click", handleNext);
buttonPrev && buttonPrev.addEventListener("click", handlePrev);
}
Navigate()
tabContainer.setAttribute("role", "tablist");
Array.prototype.forEach.call(tabs, (tab) => {
if (tab.dataset.open === "true") this.toggleTabs(tab, panels);
tab.setAttribute("role", "tab");
tab.setAttribute(
"aria-controls",
`panel-${tab.dataset.target}-block-${index + 1}`
);
const associatedPanel = tabBlock.querySelector(
`[data-panel="${tab.dataset.target}"]`
);
if (associatedPanel !== null) {
associatedPanel.id = `panel-${tab.dataset.target}-block-${
index + 1
}`;
tab.id = `tab-${tab.dataset.target}-block-${index + 1}`;
}
tab.addEventListener("click", () => {
this.toggleTabs(tab, panels);
});
});
Array.prototype.forEach.call(panels, (panel) => {
const associatedTab = tabBlock.querySelector(
`[data-target="${panel.dataset.panel}"]`
);
panel.setAttribute("role", "tabpanel");
panel.setAttribute("aria-labelledby", `${associatedTab.id}`);
});
});
}
}
toggleTabs = (currentTab, panels, buttonNext, buttonPrev) => {
const tabs = currentTab.closest(".tabs-block").querySelectorAll("button");
const target = currentTab.dataset.target;
Array.prototype.forEach.call(tabs, (tab) => {
if (tab.dataset.target !== target) {
tab.classList.remove("is-active");
tab.setAttribute("aria-selected", "false");
}
});
Array.prototype.forEach.call(panels, (panel) => {
if (panel.dataset.panel !== target) {
panel.classList.remove("is-active");
} else {
panel.classList.add("is-active");
currentTab.classList.add("is-active");
currentTab.setAttribute("aria-selected", "true");
}
});
};
}
const components = {
Tabs: new Tabs()
};
components.Tabs.init();

laravel undefined offset 0 laravel 8 resources

hello i have this error : Undefined offset: 0 (View: /home/me/www/me/resources/views/contact.blade.php) i was try to create crud in admin panel for contact page. when i try to go in for edit this page, i have this error
Undefined offset: 0 (View: /home/.../www/.../resources/views/contact.blade.php) and if i remplace all data by {{ dd($data) }} i have this
Address
<script> Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style'), rxEsc = /([.*+?^${}()|\[\]\/\\])/g, idRx = /\bsf-dump-\d+-ref[012]\w+\b/, keyHint = 0 <= navigator.platform.toUpperCase().indexOf('MAC') ? 'Cmd' : 'Ctrl', addEventListener = function (e, n, cb) { e.addEventListener(n, cb, false); }; (doc.documentElement.firstElementChild || doc.documentElement.children[0]).appendChild(refStyle); if (!doc.addEventListener) { addEventListener = function (element, eventName, callback) { element.attachEvent('on' + eventName, function (e) { e.preventDefault = function () {e.returnValue = false;}; e.target = e.srcElement; callback(e); }); }; } function toggle(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className, arrow, newClass; if (/\bsf-dump-compact\b/.test(oldClass)) { arrow = '▼'; newClass = 'sf-dump-expanded'; } else if (/\bsf-dump-expanded\b/.test(oldClass)) { arrow = '▶'; newClass = 'sf-dump-compact'; } else { return false; } if (doc.createEvent && s.dispatchEvent) { var event = doc.createEvent('Event'); event.initEvent('sf-dump-expanded' === newClass ? 'sfbeforedumpexpand' : 'sfbeforedumpcollapse', true, false); s.dispatchEvent(event); } a.lastChild.innerHTML = arrow; s.className = s.className.replace(/\bsf-dump-(compact|expanded)\b/, newClass); if (recursive) { try { a = s.querySelectorAll('.'+oldClass); for (s = 0; s < a.length; ++s) { if (-1 == a[s].className.indexOf(newClass)) { a[s].className = newClass; a[s].previousSibling.lastChild.innerHTML = arrow; } } } catch (e) { } } return true; }; function collapse(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className; if (/\bsf-dump-expanded\b/.test(oldClass)) { toggle(a, recursive); return true; } return false; }; function expand(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className; if (/\bsf-dump-compact\b/.test(oldClass)) { toggle(a, recursive); return true; } return false; }; function collapseAll(root) { var a = root.querySelector('a.sf-dump-toggle'); if (a) { collapse(a, true); expand(a); return true; } return false; } function reveal(node) { var previous, parents = []; while ((node = node.parentNode || {}) && (previous = node.previousSibling) && 'A' === previous.tagName) { parents.push(previous); } if (0 !== parents.length) { parents.forEach(function (parent) { expand(parent); }); return true; } return false; } function highlight(root, activeNode, nodes) { resetHighlightedNodes(root); Array.from(nodes||[]).forEach(function (node) { if (!/\bsf-dump-highlight\b/.test(node.className)) { node.className = node.className + ' sf-dump-highlight'; } }); if (!/\bsf-dump-highlight-active\b/.test(activeNode.className)) { activeNode.className = activeNode.className + ' sf-dump-highlight-active'; } } function resetHighlightedNodes(root) { Array.from(root.querySelectorAll('.sf-dump-str, .sf-dump-key, .sf-dump-public, .sf-dump-protected, .sf-dump-private')).forEach(function (strNode) { strNode.className = strNode.className.replace(/\bsf-dump-highlight\b/, ''); strNode.className = strNode.className.replace(/\bsf-dump-highlight-active\b/, ''); }); } return function (root, x) { root = doc.getElementById(root); var indentRx = new RegExp('^('+(root.getAttribute('data-indent-pad') || ' ').replace(rxEsc, '\\$1')+')+', 'm'), options = {
options.maxDepth)) { toggle(a); } } else if (/\bsf-dump-ref\b/.test(elt.className) && (a = elt.getAttribute('href'))) { a = a.substr(1); elt.className += ' '+a; if (/[\[{]$/.test(elt.previousSibling.nodeValue)) { a = a != elt.nextSibling.id && doc.getElementById(a); try { s = a.nextSibling; elt.appendChild(a); s.parentNode.insertBefore(a, s); if (/^[##]/.test(elt.innerHTML)) { elt.innerHTML += ' ▶'; } else { elt.innerHTML = '▶'; elt.className = 'sf-dump-ref'; } elt.className += ' sf-dump-toggle'; } catch (e) { if ('&' == elt.innerHTML.charAt(0)) { elt.innerHTML = '…'; elt.className = 'sf-dump-ref'; } } } } } if (doc.evaluate && Array.from && root.children.length > 1) { root.setAttribute('tabindex', 0); SearchState = function () { this.nodes = []; this.idx = 0; }; SearchState.prototype = { next: function () { if (this.isEmpty()) { return this.current(); } this.idx = this.idx < (this.nodes.length - 1) ? this.idx + 1 : 0; return this.current(); }, previous: function () { if (this.isEmpty()) { return this.current(); } this.idx = this.idx > 0 ? this.idx - 1 : (this.nodes.length - 1); return this.current(); }, isEmpty: function () { return 0 === this.count(); }, current: function () { if (this.isEmpty()) { return null; } return this.nodes[this.idx]; }, reset: function () { this.nodes = []; this.idx = 0; }, count: function () { return this.nodes.length; }, }; function showCurrent(state) { var currentNode = state.current(), currentRect, searchRect; if (currentNode) { reveal(currentNode); highlight(root, currentNode, state.nodes); if ('scrollIntoView' in currentNode) { currentNode.scrollIntoView(true); currentRect = currentNode.getBoundingClientRect(); searchRect = search.getBoundingClientRect(); if (currentRect.top < (searchRect.top + searchRect.height)) { window.scrollBy(0, -(searchRect.top + searchRect.height + 5)); } } } counter.textContent = (state.isEmpty() ? 0 : state.idx + 1) + ' of ' + state.count(); } var search = doc.createElement('div'); search.className = 'sf-dump-search-wrapper sf-dump-search-hidden'; search.innerHTML = '
0 of 0<\/span> '+h+' ◀'+ ''+elt.innerHTML+' ▶'; } } } catch (e) { } }; })(document);
Illuminate\Database\Eloquent\Collection {#1218
#items: []
}
contact blade
<?php
/**
* Created by PhpStorm.
* User: abhi
* Date: 10/20/2020
* Time: 5:54 PM
*/?>
#extends('layouts.app')
<style>
body {
font-family: "Lato", sans-serif;
}
.sidenav {
height: 100%;
width: 160px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
overflow-x: hidden;
padding-top: 20px;
}
.sidenav a {
padding: 6px 8px 6px 16px;
text-decoration: none;
font-size: 25px;
color: #818181;
display: block;
}
.sidenav a:hover {
color: #f1f1f1;
}
.main {
margin-left: 160px; /* Same as the width of the sidenav */
font-size: 28px; /* Increased text to enable scrolling */
padding: 0px 10px;
}
#media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}
</style>
#section('content')
<!-- CSS only -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
{{--<div class="sidenav">--}}
{{--Post--}}
{{--Categories--}}
{{--Footer--}}
{{--Society--}}
{{--</div>--}}
<section style="padding-top:60px;">
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<div class="card">
<div class="card-header">
Update Contact Details...
</div>
<div class="card-body">
#if(Session::has('status'))
<div class="alert alert-success" role="alert">
{{Session::get('status')}}
</div>
#endif
<form id="insert" method="POST" action="{{url('updatecontact')}}"
enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="h1">Address</label>
<input type="text" value="{{$data[0]->address}}" name="address" class="form-control"/>
<label for="h2">Contact(1)</label>
<input type="tel" value="{{$data[0]->contact1}}" name="contact1" class="form-control"/>
<label for="h2">Contact(2)</label>
<input type="tel" value="{{$data[0]->contact2}}" name="contact2" class="form-control"/>
<label for="h2">Fax</label>
<input type="tel" value="{{$data[0]->fax}}" name="fax" class="form-control"/>
<label for="h2">E-mail</label>
<input type="email" value="{{$data[0]->email}}" name="email" class="form-control"/>
<br>
<input type="hidden" value="{{$data[0]->id}}" name="rowid">
</div>
<button type="submit" class="btn btn-primary">Update Details</button>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"></script>
<script>
function previewFile1(input) {
var file1 = $(input).get(0).files[0];
if (file1) {
var reader = new FileReader();
reader.onload = function () {
$('#previewImg1').attr("src", reader.result);
}
reader.readAsDataURL(file1);
}
}
</script>
#endsection
controller
<?php
namespace App\Http\Controllers;
use App\Mail\ContactMail;
use App\Models\Contact;
use App\Models\ContactDetails;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
class ContactController extends Controller
{
function index(){
$this->middleware('auth');
$data['data'] = Contact::all();
return view('contact', $data);
}
function updateContact(Request $request){
$this->middleware('auth');
$data['address'] = $request->address;
$data['contact1'] = $request->contact1;
$data['contact2'] = $request->contact2;
$data['fax'] = $request->fax;
$data['email'] = $request->email;
$affected = DB::table('contacts')
->where('id', '=', $request->rowid)
->update($data);
return back()->with('status', 'Contact Details are Updated');
}
function sendContact(Request $request){
$contact = new ContactDetails();
$contact->name = $request->name;
$contact->email = $request->email;
$contact->phone = $request->phone;
$contact->msg = $request->message;
$contact->save();
$dataObject = new \stdClass();
$dataObject->name = $request->name;
$dataObject->email = $request->email;
$dataObject->phone = $request->phone;
$dataObject->msg = $request->message;
Mail::to('mokoch.web#gmail.com')->send(new ContactMail($dataObject));
return back()->with('status', 'Contact Details are Updated');
}
}
i try to create update for contact and i was hosted this but i have this i dont know how resolve... because crud for footer and other work whithout problem. it's in laravel 8
Honestly I would refactor the following
$data['data'] = Contact::all();
to
$contacts = Contact::all();
Remember that Contact::all(); is going to return an array of collections so you would need to loop through $contacts on your index view.
if you are trying to update a contact you need to get the specific contact first for example:
$contact = Contact::find($id);
Then in your blade you can simply use $contact->email instead of $data[0]->email
So in your situation you need to create a show method that accepts an id as a parameter then you can find the record you want to update and use the example above.
A good resource if you are new CodersTape

JS/Jquery - Parallax Scrolling Effect lagging and slow

I have a parallax function for a slide section of my page with 3 background images. For some reasons it is appearing quite laggy and slow when I scroll and sometimes it's hard to scroll to the 3rd background image or if I'm already at 3rd background I can't seem to scroll up again. If I scrolled up to the first background I seem to be stuck on this section and I can't go to the section above it. Not sure where I went wrong.
Here's my js:
(function ($) {
var types = ['DOMMouseScroll', 'mousewheel'];
if ($.event.fixHooks) {
for (var i = types.length; i;) {
$.event.fixHooks[types[--i]] = $.event.mouseHooks;
}
}
$.event.special.mousewheel = {
setup: function () {
if (this.addEventListener) {
for (var i = types.length; i;) {
this.addEventListener(types[--i], handler, false);
}
} else {
this.onmousewheel = handler;
}
}
, teardown: function () {
if (this.removeEventListener) {
for (var i = types.length; i;) {
this.removeEventListener(types[--i], handler, false);
}
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function (fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
}
, unmousewheel: function (fn) {
return this.unbind("mousewheel", fn);
}
});
function handler(event) {
var orgEvent = event || window.event
, args = [].slice.call(arguments, 1)
, delta = 0
, returnValue = true
, deltaX = 0
, deltaY = 0;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
if (orgEvent.wheelDelta) {
delta = orgEvent.wheelDelta / 120;
}
if (orgEvent.detail) {
delta = -orgEvent.detail / 3;
}
deltaY = delta;
if (orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS) {
deltaY = 0;
deltaX = -1 * delta;
}
if (orgEvent.wheelDeltaY !== undefined) {
deltaY = orgEvent.wheelDeltaY / 120;
}
if (orgEvent.wheelDeltaX !== undefined) {
deltaX = -1 * orgEvent.wheelDeltaX / 120;
}
args.unshift(event, delta, deltaX, deltaY);
return ($.event.dispatch || $.event.handle).apply(this, args);
}
})(jQuery);
var Parallax = {
utils: {
doSlide: function (section) {
var top = section.position().top;
$('#section-wrapper').stop().animate({
top: -top
}, 600, 'linear', function () {
section.addClass('slided').siblings('div.section').removeClass('slided');
});
}
}
, fn: {
setHeights: function () {
$('div.section').height($(window).height());
}
, onSiteScroll: function () {
var section = null;
$('#section-wrapper').mousewheel(function (event, delta) {
event.preventDefault();
if (delta < 0) {
section = ($('.slided').length) ? $('.slided') : $('#section-1');
var next = (section.next().length) ? section.next() : $('#section-1');
Parallax.utils.doSlide(next);
} else if (delta > 0) {
section = ($('.slided').length) ? $('.slided') : $('#section-1');
var prev = (section.prev().length) ? section.prev() : $('#section-1');
Parallax.utils.doSlide(prev);
}
});
}
},
init: function () {
for (var prop in this.fn) {
if (typeof this.fn[prop] === 'function') {
this.fn[prop]();
}
}
}
};
Parallax.init();
The css here:
#site {
width: 100%;
height: 100%;
min-height: 100%;
}
#section-wrapper {
position: relative;
width: 100%;
height: 100%;
min-height: 100%;
}
div.section {
width: 100%;
position: relative;
height: 100%;
min-height: 100%;
}
#section-1 {
background: url("../img/teavana/slide1.png");
}
#section-2 {
background: url("../img/teavana/slide2.png");
}
#section-3 {
background: url("../img/teavana/slide3.png");
}
And this is the html for the section:
<div id="site">
<div id="section-wrapper">
<div class="section" id="section-1"></div>
<div class="section" id="section-2"></div>
<div class="section" id="section-3"></div>
</div>
</div>

jQuery Slider to auto slide between navigation links

I have a jQuery slider on my website.
I managed to make the slider move automatically between only two navigation links, however there are four navigation links.
How can I make it that it moves orderwise from the first navigation link till the fourth link with a defined delay.
Here is the HTML code with the navigation links at the bottom:
<div id="mi-slider" class="mi-slider">
<ul>
<li><img src="images/1.jpg" alt="img01"><h4>Boots</h4></li>
<li><img src="images/2.jpg" alt="img02"><h4>Oxfords</h4></li>
<li><img src="images/3.jpg" alt="img03"><h4>Loafers</h4></li>
<li><img src="images/4.jpg" alt="img04"><h4>Sneakers</h4></li>
</ul>
<ul>
<li><img src="images/5.jpg" alt="img05"><h4>Belts</h4></li>
<li><img src="images/6.jpg" alt="img06"><h4>Hats & Caps</h4></li>
<li><img src="images/7.jpg" alt="img07"><h4>Sunglasses</h4></li>
<li><img src="images/8.jpg" alt="img08"><h4>Scarves</h4></li>
</ul>
<ul>
<li><img src="images/9.jpg" alt="img09"><h4>Casual</h4></li>
<li><img src="images/10.jpg" alt="img10"><h4>Luxury</h4></li>
<li><img src="images/11.jpg" alt="img11"><h4>Sport</h4></li>
</ul>
<ul>
<li><img src="images/12.jpg" alt="img12"><h4>Carry-Ons</h4></li>
<li><img src="images/13.jpg" alt="img13"><h4>Duffel Bags</h4></li>
<li><img src="images/14.jpg" alt="img14"><h4>Laptop Bags</h4></li>
<li><img src="images/15.jpg" alt="img15"><h4>Briefcases</h4></li>
</ul>
<nav>
Shoes
Accessories
Watches
Bags
</nav>
</div>
And the code I used to autoslide between the navigation links, but it is only switching between the first two navigation links:
;
setInterval(function () {
$('nav > a').trigger('click.catslider');
}, 12000);
});
jQuery.noConflict();
jQuery(document).ready(function ($) {;
(function ($, window, undefined) {
'use strict';
$.CatSlider = function (options, element) {
this.$el = $(element);
this._init(options);
};
$.CatSlider.prototype = {
_init: function (options) {
this.$categories = this.$el.children('ul');
this.$navcategories = this.$el.find('nav > a');
var animEndEventNames = {
'WebkitAnimation': 'webkitAnimationEnd',
'OAnimation': 'oAnimationEnd',
'msAnimation': 'MSAnimationEnd',
'animation': 'animationend'
};
this.animEndEventName = animEndEventNames[Modernizr.prefixed('animation')];
this.support = Modernizr.csstransforms && Modernizr.cssanimations;
this.isAnimating = false;
this.current = 0;
var $currcat = this.$categories.eq(0);
if (!this.support) {
this.$categories.hide();
$currcat.show();
} else {
$currcat.addClass('mi-current');
}
this.$navcategories.eq(0).addClass('mi-selected');
this._initEvents();
},
_initEvents: function () {
var self = this;
this.$navcategories.on('click.catslider', function () {
self.showCategory($(this).index());
return false;
});
$(window).on('resize', function () {
self.$categories.removeClass().eq(0).addClass('mi-current');
self.$navcategories.eq(self.current).removeClass('mi-selected').end().eq(0).addClass('mi-selected');
self.current = 0;
});
},
showCategory: function (catidx) {
if (catidx === this.current || this.isAnimating) {
return false;
}
this.isAnimating = true;
this.$navcategories.eq(this.current).removeClass('mi-selected').end().eq(catidx).addClass('mi-selected');
var dir = catidx > this.current ? 'right' : 'left',
toClass = dir === 'right' ? 'mi-moveToLeft' : 'mi-moveToRight',
fromClass = dir === 'right' ? 'mi-moveFromRight' : 'mi-moveFromLeft',
$currcat = this.$categories.eq(this.current),
$newcat = this.$categories.eq(catidx),
$newcatchild = $newcat.children(),
lastEnter = dir === 'right' ? $newcatchild.length - 1 : 0,
self = this;
if (this.support) {
$currcat.removeClass().addClass(toClass);
setTimeout(function () {
$newcat.removeClass().addClass(fromClass);
$newcatchild.eq(lastEnter).on(self.animEndEventName, function () {
$(this).off(self.animEndEventName);
$newcat.addClass('mi-current');
self.current = catidx;
var $this = $(this);
self.forceRedraw($this.get(0));
self.isAnimating = false;
});
}, $newcatchild.length * 90);
} else {
$currcat.hide();
$newcat.show();
this.current = catidx;
this.isAnimating = false;
}
},
forceRedraw: function (element) {
if (!element) {
return;
}
var n = document.createTextNode(' '),
position = element.style.position;
element.appendChild(n);
element.style.position = 'relative';
setTimeout(function () {
element.style.position = position;
n.parentNode.removeChild(n);
}, 25);
}
}
$.fn.catslider = function (options) {
var instance = $.data(this, 'catslider');
if (typeof options === 'string') {
var args = Array.prototype.slice.call(arguments, 1);
this.each(function () {
instance[options].apply(instance, args);
});
} else {
this.each(function () {
instance ? instance._init() : instance = $.data(this, 'catslider', new $.CatSlider(options, this));
});
}
return instance;
};
})(jQuery, window);
$(function () {
$('#mi-slider').catslider();
})
I have added the code for catslider

Categories

Resources