Changing the image source when pressing the back button - javascript

I have a slider. When clicking next button image is loading.
var t=3
function next_btn(){
t+=3;
var imgEl = document.querySelectorAll('.lazy');
for (let a = 0; a < t; a++) {
if(imgEl[a].getAttribute('data-original')) {
imgEl[a].setAttribute('src',imgEl[a].getAttribute('data-original'));
imgEl[a].removeAttribute('data-original');
}
}
}
but when clicking previous button image is not loading.
function previous_btn(){
var imgEl = document.querySelectorAll('.lazy');
for (let a =imgEl.length; a >3; a--) {
if(imgEl[a].getAttribute('data-original')) {
imgEl[a].setAttribute('src',imgEl[a].getAttribute('data-original'));
imgEl[a].removeAttribute('data-original');
}
}
}
I tried other things but it didn't work. How can I fix?

Related

I have a problem calling with my carousel codes, it keeps keeping variables for other conditions

I have tried so many method to stop this error but nothing seems to work, here is a link to my codepen: https://codepen.io/T_manuel/pen/PoKMYVx
when the page loads, I call the function but when I resize the page, Javascript seems to do the new logic also with previous logics...
const mediaQuery_1 = '(max-width:601px)';
const mediaQueryList1 = window.matchMedia(mediaQuery_1);
/carousel parent div -- to dynamically load the carousel items
// define media queries
const mediaQuery_1 = '(max-width:601px)';
// add matchMedia
const mediaQueryList1 = window.matchMedia(mediaQuery_1);
if (mediaQueryList1.matches) {
carouselFunc(); // dynamic loaded pictures
LeftArrow.classList.add("displayNone");
let indexOfImg = 0; //to be accessed for the carousel, index for first image
let endofImg = 3; //carousel use, index for next image to be displayed
otherCarouselLogic(indexOfImg, endofImg);
if (carouselPics.length > 3) {
for (i = 3; i < carouselPics.length; i++) {
carouselPics[i].classList.add("displayNone");
}
RightArrow.classList.remove("displayNone");
} else {
RightArrow.classList.add("displayNone");
}
}
else {
carouselFunc(); //dynamic loaded Pictures
LeftArrow.classList.add("displayNone");
let IndexOfImg = 0; //to be accessed for the carousel, index for first image
let EndOfImg = 4; //carousel use, index for next image to be displayed
otherCarouselLogic(IndexOfImg, EndOfImg);
if (carouselPics.length > 3) {
for (i = 4; i < carouselPics.length; i++) {
carouselPics[i].classList.add("displayNone");
}
}
// not to display carousel arrows if pics can be showed at once
if (carouselPics.length <= 4) {
RightArrow.classList.add("displayNone");
}
}
// add event Listener
mediaQueryList1.addEventListener("change", function carouselUx(event) {
if(event.matches) {
document.getElementById("carous").innerHTML = "";
carouselFunc(); //contains dynamic loaded pictures
LeftArrow.classList.add("displayNone");
let indexOfImg = 0; //to be accessed for the carousel, index for first image
let endofImg = 3; //carousel use, index for next image to be displayed
otherCarouselLogic(indexOfImg, endofImg);
if (carouselPics.length > 3) {
for (i = 3; i < carouselPics.length; i++) {
carouselPics[i].classList.add("displayNone");
}
RightArrow.classList.remove("displayNone");
} else {
RightArrow.classList.add("displayNone");
}
}
else {
document.getElementById("carous").innerHTML = "";
carouselFunc();
LeftArrow.classList.add("displayNone");
let IndexOfImg = 0; //to be accessed for the carousel, index for first image
let EndOfImg = 4; //carousel use, index for next image to be displayed
otherCarouselLogic(IndexOfImg, EndOfImg);
if (carouselPics.length > 3) {
for (i = 4; i < carouselPics.length; i++) {
carouselPics[i].classList.add("displayNone");
}
}
// not to display carousel arrows if pics can be showed at once
if (carouselPics.length <= 4) {
RightArrow.classList.add("displayNone");
}
}
})
function otherCarouselLogic(cpF, newImg) {
/* carousel code ends here */
carouselBtn.forEach(function (btns) {
btns.addEventListener("click", function (e) {
clickedArrow = e.currentTarget.id;
if (clickedArrow === "right") {
console.log(newImg);
carouselPics[cpF].classList.add("displayNone");
carouselPics[newImg].classList.remove("displayNone");
LeftArrow.classList.remove("displayNone");
cpF += 1;
newImg += 1;
}
if (clickedArrow === "left") {
cpF -= 1;
newImg -= 1;
carouselPics[newImg].classList.add("displayNone");
carouselPics[cpF].classList.remove("displayNone");
RightArrow.classList.remove("displayNone");
console.log(newImg);
}
// ux purpose, when we get to the last pics in the carousel, the right arrow is hidden
diffR = carouselPics.length - newImg;
// diffL
if (diffR === 0) {
RightArrow.classList.add("displayNone");
}
if (cpF === 0) {
LeftArrow.classList.add("displayNone");
}
});
});
/* carousel code ends here */
}
upon load,
newImg is set to 4 and all seems to work
after resize, it is set to either 3 or 4 depending on the logic, but instead of incrementing that value alone, it gives value for the load and also for the resize.

jscript for toggling a hamburger menu not working

I am trying to fix some stuff left over by the front-end developer and I am not expert in javascript (not at all).
On our staging system we use a hamburger menu and for reasons unknown to me while the hamburger menu toggles perfectly on opening, upon first closing it doesn't revert back from an "X" to the "Hamburger" subsequent changes instead work flawlessly just that the state is inverted ("X" where there should be a hamburger and hamburger where there should be an "X").
So I did it half right (but only half :D).
My rather not beautyful code:
<script type="text/javascript">
var headerMobile = document.getElementsByClassName('header-mobile')[0];
var openMobileMenuTrigger = document.getElementById('open-mobile-menu');
var closeMobileMenuTrigger = document.getElementById('close-mobile-menu');
var mobileMainMenu = document.getElementById('header-mobile_menu');
var submenus = document.getElementsByClassName('header-mobile_submenu');
var openMobileSubMenuTriggers = document.getElementsByClassName('open-mobile-submenu');
var closeMobileSubMenuTriggers = document.getElementsByClassName('close-mobile-submenu');
var hamburgerHeader = document.getElementById('open-mobile-menu');
var openSearchTrigger = document.getElementById('open-search-field')
function toggleHamburger(){
if (hamburgerHeader.classList.contains('is-active')){
hamburgerHeader.classList.remove('is-active');
} else {
hamburgerHeader.classList.add('is-active');
}
}
function toggleMobileMenu(){
if(mobileMainMenu.classList.contains('is-active') !== true){
if (openSearchTrigger)
{openSearchTrigger.classList.remove('is-active')}
mobileMainMenu.classList.add('is-active');
headerMobile.classList.add('is-active'); //remove shadow
document.getElementsByTagName('html')[0].classList.add('noscroll')// no scroll for html
document.getElementsByTagName('body')[0].classList.add('noscroll')// no scroll for body
} else {
setTimeout(
function(){
// headerMobile.classList.remove('is-active'); // NO MORE SHADOW IF WE KEEP ACTIVE SEARCH MENU
for (var i = submenus.length - 1; i >= 0; i--) {
submenus[i].classList.remove('is-active');
}
},
400
)
if(openSearchTrigger){
openSearchTrigger.classList.add('is-active')
}
hamburgerHeader.classList.remove('is-active')
mobileMainMenu.classList.remove('is-active')
document.getElementsByTagName('html')[0].classList.remove('noscroll')// no scroll for html
document.getElementsByTagName('body')[0].classList.remove('noscroll')// no scroll for body
}
}
function openMobileSubmenu(event){
var submenuId = event.currentTarget.getAttribute('data-submenu');
document.getElementById('header-mobile_submenu-' + submenuId).classList.add('is-active');
}
function closeMobileSubmenu(){
for (var i = submenus.length - 1; i >= 0; i--) {
submenus[i].classList.remove('is-active');
}
}
if (openSearchTrigger){
openSearchTrigger.addEventListener('click', toggleMobileMenu);
}
openMobileMenuTrigger.addEventListener('click', toggleMobileMenu);
// closeMobileMenuTrigger.addEventListener('click', closeMobileMenu);
hamburgerHeader.addEventListener('click', toggleHamburger);
for (var i = openMobileSubMenuTriggers.length - 1; i >= 0; i--) {
openMobileSubMenuTriggers[i].addEventListener('click', openMobileSubmenu);
}
for (var i = closeMobileSubMenuTriggers.length - 1; i >= 0; i--) {
closeMobileSubMenuTriggers[i].addEventListener('click', closeMobileSubmenu);
}

JS function only works properly after clicking on screen

I am building a title generator with HTML, CSS and JavaScript. The following code is supposed to do this:
Enter Edit-Mode with pressing of the "Enter"-Key (works correctly)
Turning down the opacity of the top left and top right box by clicking on the red buttons (works)
Hiding both items when exiting Edit-Mode by pressing "Enter" again. (works)
Enter Edit-Mode again and showing both hidden div boxes with opacity set to 20% (does not work)
Only the first box that was clicked on shows up again. It seems like the class "deactivated" is not safed for the last item being clicked on as it disappears on step 3.
However it does work when I click somewhere on the document before going to step 3.
Any help appreciated!
Full version can be found here
/*Switch between Display and Edit Mode*/
function toggleHideUI() {
var HideUI = document.getElementById("hiddenUI");
if (HideUI.style.display === "block") {
hideHiddenElements();
HideUI.style.display = "none";
} else {
showHiddenElements();
HideUI.style.display = "block";
}
};
/* EventListener for "Enter" Keybind */
document.addEventListener("keydown", (e) => {
if (e.code == "Enter") {
toggleHideUI();
}
});
/*Hide hidden elements (class = "deactivated") for Display Mode */
function hideHiddenElements() {
var HiddenElements = document.getElementsByClassName("deactivated");
for (i = 0; i < HiddenElements.length; i++) {
HiddenElements.item(i).style.display = "none";
}
};
/*Show hidden elements (class = "deactivated") for Edit Mode */
function showHiddenElements() {
var HiddenElements = document.getElementsByClassName("deactivated");
for (i = 0; i < HiddenElements.length; i++) {
HiddenElements[i].style.display = 'block';
}
}
/*Toggle DB Logo in upper left corner*/
document.getElementById("hide-db-logo").onclick = function toggleDBLogo() {
document.getElementById("db-box").classList.toggle("deactivated");
}
/*Toggle Campus Logo in upper right corner*/
document.getElementById("hide-campus-logo").onclick = function toggleCampusLogo() {
document.getElementById("campus-box").classList.toggle("deactivated");
}
I have updated the working script as:
The problem is when you click enter when the element is in focus, the event is propagating back.
<script>
/*Switch between Display and Edit Mode*/
function toggleHideUI() {
let HideUI = document.getElementById("hiddenUI");
if (HideUI.style.display === "block") {
hideHiddenElements();
HideUI.style.display = "none";
} else {
showHiddenElements();
HideUI.style.display = "block";
}
};
/* EventListener for "Enter" Keybind */
document.addEventListener("keydown", (e) => {
if (e.code == "Enter") {
e.preventDefault(); //<--- notice here
toggleHideUI();
}
});
/*Hide hidden elements (class = "deactivated") for Display Mode */
function hideHiddenElements() {
let HiddenElements = document.getElementsByClassName("deactivated"); //<--- notice here use let instead of var
for (let j = 0; j < HiddenElements.length; j++) {
HiddenElements[j].style.display = "none";
}
};
/*Show hidden elements (class = "deactivated") for Edit Mode */
function showHiddenElements() {
let HiddenElements = document.getElementsByClassName("deactivated");
//<--- notice here use let instead of var
for (let i = 0; i < HiddenElements.length; i++) {
HiddenElements[i].style.display = 'block';
}
}
/*Toggle DB Logo in upper left corner*/
document.getElementById("hide-db-logo").onclick = function toggleDBLogo() {
document.getElementById("db-box").classList.toggle("deactivated");
}
/*Toggle Campus Logo in upper right corner*/
document.getElementById("hide-campus-logo").onclick = function toggleCampusLogo() {
document.getElementById("campus-box").classList.toggle("deactivated");
}
</script>
Good Luck!

Clicking On Multiple Instances of the Same Class not Working

I have a menu button that appears multiple times on a site that i've put a click event on.
When I click on the button nothing happens (when there was just one instance of the button it worked fine). I know I need to loop through the node list created by having multiple instances of a class, but when I click on the button now, nothing happens and I don't get an error in the console either to give me any pointers?
Javascript and a simplified illustration in a Codepen are below.
Codepen: https://codepen.io/emilychews/pen/owWVGz
JS
var $mainMenuButton = document.getElementsByClassName('desktopmenubutton');
var $mainMenuButtonAll = function () {
for(h = 0; h < $mainMenuButton.length; h+=1) {
$mainMenuButton[i];
}
};
$mainMenuButtonAll.onclick = function () {
$mainMenuButtonAll.style.background = "black";
};
Any help would be awesome.
Emily
I edited the code for you, check the comments and the jsFiddle.
// get all the buttons with this tag name (or use class name)
var allButtons = document.getElementsByTagName('desktopmenubutton');
// add a click listener to each button
for(h = 0; h < allButtons.length; h+=1) {
allButtons[h].addEventListener("click", function(e){
console.log("yo yo");
e.currentTarget.style.backgroundColor = "black";
})
}
var $el = document.getElementsByClassName('desktopmenubutton');
// Solution 1
for (var i = 0; i < $el.length; i++) {
// If on clicking any element, only that should change
$el[i].onclick = function () {
this.style.background = 'black';
}
}
// Solution 2
for (var i = 0; i < $el.length; i++) {
// If on clicking any element, all should change
$el[i].onclick = function () {
for (var j = 0; j < $el.length; j++) {
$el[j].style.background = 'black'
}
}
}
First, we get all the elements and bind seperate click handlers for all the elements seperately. Solution 1 when you want to change only the element clicked and solution 2 when you want all the elements to change.
var $mainMenuButton = document.getElementsByClassName('desktopmenubutton');
var $mainMenuButtonAll = function () {
for(h = 0; h < $mainMenuButton.length; h+=1) {
$mainMenuButton[h].addEventListener("click", function(){
this.style.background = 'black';
});
}
};
$mainMenuButtonAll();
You need to bind each and every occurence of the button with an event click to perform some action over it.
var $mainMenuButton = document.getElementsByClassName('desktopmenubutton');
for(var h = 0; h < $mainMenuButton.length; h++) {
$mainMenuButton[h].addEventListener('click', function() {
this.style.background = "black";
});
}
Here is a working example.
What I did:
Removed the $mainMenuButtonAll variable since it was not needed.
Made the h variable on the for loop local, instead of global(more on that here)
Added an event listener to each $mainMenuButton, since it's never good to overwrite the onclick event.

JavaScript Image Gallery 2

I don't know if this question has been asked before or not. But...
I have the following JavaScript code in my HTML file:
<img id="imageDisplay">
<script type="text/javascript">
var displayImage = document.querySelector( '#imageDisplay' );
var imageArray = [ 'http://www.joongcho.com/Images/30th-Bday-Party-01.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-02.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-03.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-04.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-05.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-06.jpg' ];
var imageCount = 0;
var imageLength = imageArray.length;
displayImage.setAttribute( 'src', imageArray[ imageCount ] );
function nextImage(imageCount) {
}
function previousImage(imageCount) {
}
</script>
I'm trying to put a next Image and a previous Image function for this HTML.
For the next image, if there are more than 1 images and the image is not the last image, then there should be a link that allows a user to click through the array forwards. Also, if the image is the last image in the array, then the link is hidden.
For the previous image, if the image is not the first image of the array, then there should be a link that allows a user click through the array backwards. if the image is the first image, then the previous link should be hidden.
Any help is appreciated.
You have to attach event listeners to buttons or links (I used buttons):
var displayImage = document.getElementById('imageDisplay');
var buttonPrev = document.getElementById('button-prev');
var buttonNext = document.getElementById('button-next');
var imageArray = [ '../Images/30th-Bday-Party-01.jpg',
'../Images/30th-Bday-Party-02.jpg',
'../Images/30th-Bday-Party-03.jpg',
'../Images/30th-Bday-Party-04.jpg',
'../Images/30th-Bday-Party-05.jpg',
'../Images/30th-Bday-Party-06.jpg' ];
var imageCount = 0;
var imageLength = imageArray.length;
function nextImage () {
imageCount++;
if (imageCount >= imageLength - 1) {
buttonNext.style.display = 'none';
imageCount = imageLength - 1;
}
if (imageCount < imageLength) {
displayImage.setAttribute('src', imageArray[imageCount]);
}
if (imageCount > 0) {
buttonPrev.style.display = 'inline';
}
}
function previousImage () {
imageCount--;
if (imageCount <= 0) {
buttonPrev.style.display = 'none';
imageCount = 0;
}
if (imageCount >= 0) {
displayImage.setAttribute('src', imageArray[imageCount]);
}
if (imageCount < imageLength) {
buttonNext.style.display = 'inline';
}
}
displayImage.setAttribute('src', imageArray[imageCount]);
displayImage.textContent = imageCount;
buttonPrev.style.display = 'none';
buttonNext.addEventListener('click', nextImage);
buttonPrev.addEventListener('click', previousImage);
<img id="imageDisplay" />
<button id="button-prev">Back</button>
<button id="button-next">Forward</button>
Of course, you can't look at the images yet.

Categories

Resources