why show() method does not work in jQuery? - javascript

I am trying to create a very simple slideshow using jQuery code with only 3 pictures.
I use the next() method to show the next image. This is how it should work:
When you click on a link (class="next"), a method is called which hides the current image and shows the next image and adds 1 to a counter (i) unless a 3rd image. Then, it hides the current image and shows first image (id="first").
It's OK when you click on the first or second image and works correctly, but when you click on the 3rd image, it just hides the current image but it doesn't show first picture.
var a = new Array();
$("#slideShow").children().first().show();
$("#slideShow").children().first().next().hide();
$("#slideShow").children("div").last().hide();
var i = 0
$(".next").click(function() {
if (i == 2) {
$(this).parent().hide();
$("#first").show();
i = 0;
} else {
$(this).hide();
$(this).siblings().hide();
$(this).parent().next().show();
i++;
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=slideShow>
<div id="first">
<img src="https://i.stack.imgur.com/XZ4V5.jpg">
<a class="prev">❮</a>
<a class="next">❯</a>
</div>
<div>
<img src="https://i.stack.imgur.com/7bI1Y.jpg">
<a class="prev">❮</a>
<a class="next">❯</a>
</div>
<div>
<img src="https://i.stack.imgur.com/lxthA.jpg">
<a class="prev">❮</a>
<a class="next">❯</a>
</div>
</div>
These are some ways I tried:
Using css({"display":"block"}) instead of show() in jQuery
Using Javascript syntax instead of jQuery: document.getElementById("first").show();
Traversing instead of using id: $(this).parent().parent().show;
However these didn't work.

Your logic isn't quite correct as you hide the content of the slide div, then try and call show() on the slide div, not its content.
A better approach is to use a class to track the active slide and move to the next() one on button click:
let $slides = $('#slideShow > div');
$(".next").click(function() {
let $current = $slides.filter('.active').removeClass('active');
let $target = $current.next('div');
if (!$target.length)
$target = $slides.first();
$target.addClass('active');
})
#slideShow > div {
display: none;
}
#slideShow div.active {
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="slideShow">
<div class="active">
Screen 1
<img src="img\Screenshot (1).png">
</div>
<div>
Screen 4
<img src="img\Screenshot (4).png">
</div>
<div>
Screen 15
<img src="img\Screenshot (15).png">
</div>
<a class="prev">❮</a>
<a class="next">❯</a>
</div>

The problem is that you show() the parent <div> but you also hide() the <img> / <a> children and never show() them again.
Remove:
$(this).hide();
$(this).siblings().hide();
and add:
$(this).parent().hide();
then you should be ok. Without changing any of your other logic, this gives:
var a = new Array();
//$("#slideShow").children().first().show();
//$("#slideShow").children().first().next().hide();
//$("#slideShow").children("div").last().hide();
$("#slideShow>div").hide().first().show();
var i = 0
$(".next").click(function() {
if (i == 2) {
$(this).parent().hide();
$("#first").show();
i = 0;
} else {
//$(this).hide();
//$(this).siblings().hide();
$(this).parent().hide();
$(this).parent().next().show();
i++;
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=slideShow>
<div id="first">
<img src="https://i.stack.imgur.com/XZ4V5.jpg" width=200>
<a class="prev">❮</a>
<a class="next">❯</a>
</div>
<div>
<img src="https://i.stack.imgur.com/7bI1Y.jpg" width=200>
<a class="prev">❮</a>
<a class="next">❯</a>
</div>
<div>
<img src="https://i.stack.imgur.com/lxthA.jpg" width=200>
<a class="prev">❮</a>
<a class="next">❯</a>
</div>
</div>

I would recommend SwiperJS
However, this might be a quick solution to your problem
$(".prev").click(function() {
//go to previous slide
var activeSlide = $("div.active"),
previousSlide = activeSlide.prev()
//check if there is previous slide
if (previousSlide.length !== 0) {
activeSlide.removeClass("active")
previousSlide.addClass("active")
} else {
alert("there is no previous slide!")
}
})
$(".next").click(function() {
//go to next slide
var activeSlide = $("div.active"),
nextSlide = activeSlide.next()
//check if there is next slide
if (nextSlide.length !== 0) {
activeSlide.removeClass("active")
nextSlide.addClass("active")
} else {
alert("there is no next slide!")
}
})
#slideShow > div{
display:none;
overflow:hidden;
height:120pt;
width:250pt;
}
#slideShow > div img{
width:100%;
}
#slideShow > div.active{
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id=slideShow>
<div class="active">
<img src="img\Screenshot (1).png" alt="slide1">
</div>
<div>
<img src="img\Screenshot (4).png" alt="slide 2">
</div>
<div>
<img src="img\Screenshot (15).png" alt="slide 3">
</div>
</div>
<a class="prev">❮</a>
<a class="next">❯</a>

Related

Problems with showing my screens and functions to work in javascript/html

I am trying to get my screens and functions to work correctly. I am now stuck at the start page of my website/game.
I have two problems:
It seems that my click events don't work, nothing happens when I press my start buttons. After I've pressed them I then want the actual game to show up which is my "game_start".
After I press my start buttons, I want the "game_start" id screen to be hidden and the actual "game" id screen to show up.
Thankful for the help //rookie
window.addEventListener("load", start);
function startscreen() {
//unhide screens
document.querySelector("#game_start").classList.remove("hidden");
//EventListeners
document.querySelector("#start_button").addEventListener("click", StartGame);
document.querySelector("#start_button_2").addEventListener("click", StartGame);
}
function StartGame() {
console.log("StartGame");
//hide screens
document.querySelector("game_start").classList.add("hidden");
//add screens
document.querySelector("#game").classList.remove("hidden");
}
<div id="game_start" class="hidden">
<img src="Assets copy.SVG/HOMESCREEN.svg" alt="Start">
<div id="start_button" alt="start">
<span class="blink"><img src="Assets copy.SVG/START.GREEN.svg"></span></a>
</div>
<div id="start_button_2" alt="start">
<img src="Assets copy.SVG/START.GREY.svg"></a>
</div>
</div>
<div id="game" class="hidden">
<div id="game_consol"> <img src="Assets copy.SVG/GAME_CONSOL.svg" alt="GameConsol"></div>
<div id="game_foreground"> <img src="Assets copy.SVG/STARS.svg" alt="GameForeground"></div>
<div id="game_background"> <img src="Assets copy.SVG/BACKGROUND.svg" alt="GameBackground"></div>
</div>
Is this what you were looking for?
I assume on window load you want to invoke startscreen. Then remove the game_start div and display the game div when button start_button is clicked right?
window.addEventListener("load", startscreen);
function startscreen() {
//unhide screens
document.querySelector("#game_start").classList.remove("hidden");
//EventListeners
document.querySelector("#start_button").addEventListener("click", StartGame);
document.querySelector("#start_button_2").addEventListener("click", StartGame);
}
function StartGame() {
console.log("StartGame");
//hide screens
document.querySelector("#game_start").classList.add("hidden");
//add screens
document.querySelector("#game").classList.remove("hidden");
}
.hidden {
display: none;
}
<div id="game_start" class="hidden">
<img src="https://placekitten.com/g/100/100" alt="Start">
<div id="start_button" alt="start">
<span class="blink"><img src="https://placekitten.com/100/100"></span></a>
</div>
<div id="start_button_2" alt="start">
<img src="https://placekitten.com/g/100/100"></a>
</div>
</div>
<div id="game" class="hidden">
<div id="game_consol"> <img src="https://placekitten.com/100/100" alt="GameConsol"></div>
<div id="game_foreground"> <img src="https://placekitten.com/g/100/100" alt="GameForeground"></div>
<div id="game_background"> <img src="https://placekitten.com/100/100" alt="GameBackground"></div>
</div>
addEventListener("load", start);
but I dont seen any start function in your code!!!
window.addEventListener("load", startscreen());
and of course dont forget StartGame call your function.
You need to pay more attention to details. In my code you can check the comments for the errors.
In javascript code:
// First Error: Where is the function "start" ?
// window.addEventListener("load", start);
and
// Second Error: Your ID selector need `#` before the name.
// document.querySelector("game_start").classList.add("hidden");
In html code you closed two link (a TAG) but it never opened.
// First Error: Where is the function "start" ?
// window.addEventListener("load", start);
window.addEventListener("load", startscreen);
function startscreen() {
//unhide screens
document.querySelector("#game_start").classList.remove("hidden");
//EventListeners
document.querySelector("#start_button").addEventListener("click", StartGame);
document.querySelector("#start_button_2").addEventListener("click", StartGame);
}
function StartGame() {
console.log("StartGame");
// Second Error: Your ID selector need # before the name.
// document.querySelector("game_start").classList.add("hidden");
//hide screens
document.querySelector("#game_start").classList.add("hidden");
//add screens
document.querySelector("#game").classList.remove("hidden");
}
.hidden {
display:none;
}
<div id="game_start" class="hidden">
<img src="https://via.placeholder.com/100x50/0055FF/fff?text=HEADER" alt="Start">
<div id="start_button" alt="start">
<span class="blink"><img src="https://via.placeholder.com/100x50/FF00FF/fff?text=buttton+1"></span><!--Where is the open ? </a> -->
</div>
<div id="start_button_2" alt="start">
<img src="https://via.placeholder.com/100x50/FF0000/fff?text=button+2"><!--Where is the open ? </a> -->
</div>
</div>
<div id="game" class="hidden">
<div id="game_consol"> <img src="https://via.placeholder.com/100x50/FF5500/fff?text=Game+Header" alt="GameConsol"></div>
<div id="game_foreground"> <img src="https://via.placeholder.com/100x50/FF0055/fff?text=Foreground" alt="GameForeground"></div>
<div id="game_background"> <img src="https://via.placeholder.com/100x50/55FF55/fff?text=Background" alt="GameBackground"></div>
</div>
window.addEventListener("load", startscreen);
function startscreen() {
//unhide screens
document.querySelector("#game_start").classList.remove("hidden");
//EventListeners
document.querySelector("#start_button").addEventListener("click", StartGame);
document.querySelector("#start_button_2").addEventListener("click", StartGame);
}
function StartGame() {
console.log("StartGame");
//hide screens
document.querySelector("#game_start").classList.add("hidden");
//add screens
document.querySelector("#game").classList.remove("hidden");
}
#start_button, #start_button_2{
cursor: pointer;
}
.hidden{
display: none;
}
<div id="game_start" class="hidden">
<img src="Assets copy.SVG/HOMESCREEN.svg" alt="Start">
<div id="start_button">
<span class="blink"><img alt="start" src="Assets copy.SVG/START.GREEN.svg"></span>
</div>
<div id="start_button_2">
<img alt="start2" src="Assets copy.SVG/START.GREY.svg">
</div>
</div>
<div id="game" class="hidden">
<div id="game_consol"> <img src="Assets copy.SVG/GAME_CONSOL.svg" alt="GameConsol"></div>
<div id="game_foreground"> <img src="Assets copy.SVG/STARS.svg" alt="GameForeground"></div>
<div id="game_background"> <img src="Assets copy.SVG/BACKGROUND.svg" alt="GameBackground"></div>
</div>
Change startscreen in the window.addEventListener("load", startscreen); and remove the random <a/>'s.
Then the document.querySelector("game_start").classList.add("hidden"); needs to have the # in it like this document.querySelector("#game_start").classList.add("hidden");

Check element is in view port using isOnScreen

I am working on a function that should get the text inside a span with class ".dida" of each post (Tumblr) and append them in a specific place (a div with id "#bottom-stripe") only when the image of the posts (img with class ".miniatura") are 50% in viewport.
I am using this external library to detect the elements on viewport:
https://github.com/moagrius/isOnScreen
This is my JS code:
<script>
$( window ).on('load scroll', function(e) {
$( "img.miniatura" ).each(function() {
if ( $( this ).isOnScreen(0.5, 0.5) ) {
var dida = $(".dida").each(function() {
$(this).html();
});
$( "#bottom-stripe" ).empty();
$( "#bottom-stripe" ).append( dida );
}
});
});
</script>
The script get all the captions together and append them all in the #bottom-stripe div. I want it to do this only when the img.miniatura are 50% in the viewport.
Any suggestions on where is the mistake?
Many thanks for your help!
It seems that you want to detect which image is currently in viewport.
$("img.miniatura").each(function() {
if ($(this).isOnScreen(0.5, 0.5)) {
var text = $(this).parents('div').find('.number').html();
//Detect which image is in viewport
$('#bottom-stripe').html(text);
}
});
I've add images text under number class, see the working example to detect the current view port image.
// https://github.com/moagrius/isOnScreen
!function(t){t.fn.isOnScreen=function(o,e){(null==o||"undefined"==typeof o)&&(o=1),(null==e||"undefined"==typeof e)&&(e=1);var i=t(window),r={top:i.scrollTop(),left:i.scrollLeft()};r.right=r.left+i.width(),r.bottom=r.top+i.height();var f=this.outerHeight(),n=this.outerWidth();if(!n||!f)return!1;var h=this.offset();h.right=h.left+n,h.bottom=h.top+f;var l=!(r.right<h.left||r.left>h.right||r.bottom<h.top||r.top>h.bottom);if(!l)return!1;var m={top:Math.min(1,(h.bottom-r.top)/f),bottom:Math.min(1,(r.bottom-h.top)/f),left:Math.min(1,(h.right-r.left)/n),right:Math.min(1,(r.right-h.left)/n)};return m.left*m.right>=o&&m.top*m.bottom>=e}}(jQuery);
// show only captions related to visible images
$(window).on('load scroll', function(e) {
$( "img.miniatura" ).each(function() {
if ($(this).isOnScreen(0.5, 0.5)) {
var text = $(this).parents('div').find('.number').html();
//Detect which image is in viewport
$('#bottom-stripe').html(text);
}
});
});
.info ul.tags {
display: none;
}
#bottom-stripe {
width: 100%;
height: auto;
position: fixed;
bottom: 0px;
left: 0px;
background-color: #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="post">
<div class="post-content">
<div class="media">
<a href="#">
<img class="miniatura" src="https://placehold.it/350x300">
</a>
<div class="number">First Image</div>
<div class="info">
<ul class="tags">
<li>FirstWord</li>
<li>SecondWord</li>
<li>ThirdWord</li>
</ul>
</div>
</div>
</div>
</div>
<div class="post">
<div class="post-content">
<div class="media">
<a href="#">
<img class="miniatura" src="https://placehold.it/350x300">
</a>
<div class="number">Second Image</div>
<div class="info">
<ul class="tags">
<li>FirstWord</li>
<li>SecondWord</li>
<li>ThirdWord</li>
<li>FourthWord</li>
</ul>
</div>
</div>
</div>
</div>
<div class="post">
<div class="post-content">
<div class="media">
<a href="#">
<img class="miniatura" src="https://placehold.it/350x300">
</a>
<div class="number">Third Image</div>
<div class="info">
<ul class="tags">
<li>FirstWord</li>
<li>SecondWord</li>
<li>ThirdWord</li>
</ul>
</div>
</div>
</div>
</div>
<div id="bottom-stripe">test</div>

How to remove data-toggle="modal" in specific window size?

I am a beginner of the javascript. I want to remove the data-toggle attribute when the screen size is less than 760px and make the href working. I have no idea how to remove the data-toggle attribute, below is my code:
<div class="portfolio logo1 mix_all" data-cat="logo" style="display: inline-block; opacity: 1;">
<div class="portfolio-wrapper">
<a data-toggle="modal" data-target="#myModal1" href="http://www.example.com/main/includes/onepager/business_service/example/index.php" class="b-link-stripe b-animate-go thickbox">
<img class="p-img" src="http://www.example.com/theme/mobile-page-files/web/images/small-portfolio/example.JPG" />
<div class="b-wrapper">
<h2 class="b-animate b-from-left b-delay03">
<img src="http://www.example.com/theme/mobile-page-files/web/images/link-ico.png" alt=""/>
</h2>
</div>
</a>
</div>
<div class="port-info">
<h4>
Example
</h4>
</div>
</div
At the bottom of your page (just before the </body> tag) add the following code :
if(window.innerWidth < 760){
document.getElementsByTagName("a")[0].removeAttribute("data-toggle");
}
Nobody addressed the case when the screen width might again be greater than 760. We'll have to add the data attribute back.
window.addEventListener("resize", resizeHandler);
function resizeHandler() {
var winWidth = window.innerWidth,
threshold = 760,
els = document.getElementsByClassName('thickbox');
[].forEach.call(els, function (el) {
if (winWidth < threshold) {
el.removeAttribute("data-toggle");
} else {
el.setAttribute("data-toggle", "bar");
}
});
}
Check out this tiny demo to see it in action. http://codepen.io/antibland/pen/reZNNO
You can use a bit of jQuery... Don't forget to update the selector ELEMENTID
if($(window).width() < 760){
$('#ELEMENTID').find('a').removeAttr('data-toggle');
}

equial height not working properly?

Hello I have tried doing the equal heights js code but its not working for me somehow,
this is my js fiddle: jsfiddle
I think im missing something with the classes?
Thanks in advance for any help
this is my html:
// equal heights - plugin
;(function($) {
$.fn.equalHeights = function() {
var maxHeight = 0,
$this = $(this);
$this.each( function() {
var height = $(this).innerHeight();
if ( height > maxHeight ) { maxHeight = height; }
});
return $this.css('height', maxHeight);
};
})(jQuery);
$(document).ready(function(){
var equaliseMozaic = function(){
$('.jury-president__block').equalHeights();
console.log('reset');
};
// make mozaic blocks equal heights
if( $('.jury-president__block').length > 0 ){
// equalise mozaic blocks
equaliseMozaic();
// equalise mozaic blocks on resize
var throttledequaliseMozaic = _.throttle(equaliseMozaic, 500);
$(window).resize(throttledequaliseMozaic);
}
});
.jury-blocks{}
.jury-president__block{width:100px; display: inline-block; background-color:gray;}
.jury-president__block img {width:50px;}
<div class="jury-blocks">
<div class="jury-president__block grid-20">
<a href="">
<img src="http://placekitten.com/g/300/300" alt="">
</a>
<div class="jury-president__category"> Name<br>erwer</div>
<div class="jury-president__name"> Name, Juror Company</div>
</div>
<div class="jury-president__block grid-20">
<a href="">
<!--- <img src="http://placekitten.com/g/300/300" alt=""> --->
<img src="http://placekitten.com/g/300/300" alt="">
</a>
<div class="jury-president__category"> Name</div>
<div class="jury-president__name"> Name, Juror Company</div>
</div>
<div class="jury-president__block grid-20">
<a href="">
<!--- <img src="/assets/images/female-silhouette.jpg" alt=""> --->
<img src="http://placekitten.com/g/300/300" alt="">
</a>
<div class="jury-president__category"> Name</div>
<div class="jury-president__name"> Name, Company</div>
</div>
Adding this seems to make it work:
.jury-blocks{display:flex;}
Does this plunk have the behavior you were looking for? http://plnkr.co/edit/mPCw3Firht2lbdEMRCpn?p=preview If not, I can try again.
Additionally, your fiddle did not include jQuery or underscore, both of which appear to be necessary. Once I included those in my plunk, the heights were correct, the divs were just not all positioned correctly.
Add CSS
.jury-blocks { display: table; }
.jury-president__block{ display:table-cell; vertical-align:top;}
No need of JS

jquery toggle between divs and subsequently hide active div

a play on a similar question asked by me that was graciously answered.
three divs, all hidden. jquery toggles between them via different links. this works great! now, i'd like to clink the link corresponding to the active div and hide it, esentially the same as when the page loads with all of them hidden. right now it fades out and back in.
help! thank you!
HTML:
<div id="nav">
<a class="home" id="show_about" title="About">ABOUT</a><br />
<a class="home" id="show_subscribe" title="Subscribe">SUBSCRIBE</a><br />
<a class="home" id="show_contact" title="Contact">CONTACT</a>
</div>
<div id="content">
<div class="current" id="about">
<p>ABOUT's content</p>
</div>
<div id="subscribe">
<p>SUBSCRIBE's content</p>
</div>
<div id="contact">
<p>CONTACT's content</p>
</div>
</div>
Javascript:
$(function(){
$('#about').css('display', 'none');
$('#subscribe').css('display', 'none');
$('#contact').css('display', 'none');
});
$('.home').click(function(){
var id = $(this).html().toLowerCase();
$('.current').fadeOut(600, function(){
$('#'+id).fadeIn(600);
$('.current').removeClass('current');
$('#'+id).addClass('current');
});
});
Try this out..
Since on fadeOut the current class is removed, if the size of current is 0 it means nothing is selected. We can simply fadeIn the content div.
$('#about, #subscribe, #contact').hide();
$('.home').click(function() {
var id = $(this).html().toLowerCase();
var $content = $('#' + id + ':not(:visible)');
if ($('.current').length === 0) {
showContent($content)
}
else {
$('.current').fadeOut(600, function(){showContent($content)});
}
});
function showContent(content) {
content.fadeIn(600);
$('.current').removeClass('current');
content.addClass('current');
}
Example on jsfiddle.
Here is another approach:
$(function(){
$('#content div').hide();
});
$('.home').click(function(){
var targetSelector = '#' + $(this).attr('title').toLowerCase();
var targetShown = $(targetSelector).is(':visible');
if (targetShown) {
$(targetSelector).fadeOut(600);
} else {
$('#content div:not(' + targetSelector + ')').fadeOut(600,
function() {$(targetSelector).fadeIn(600)});
}
});
Check to see if the id of the clicked element is equal to the id of the element currently being displayed (i.e. the element with the current class). If it is a different element, then a swap needs to take place. If it is the same element, then it needs to be hidden and have its current class removed...
(Edit: fixed code)
HTML:
<div id="nav">
<a class="home" id="show_about" title="About">ABOUT</a><br />
<a class="home" id="show_subscribe" title="Subscribe">SUBSCRIBE</a><br />
<a class="home" id="show_contact" title="Contact">CONTACT</a>
</div>
<br />
<br />
<br />
<div id="content">
<div id="about">
<p>ABOUT's content</p>
</div>
<div id="subscribe">
<p>SUBSCRIBE's content</p>
</div>
<div id="contact">
<p>CONTACT's content</p>
</div>
<div class="current" id="dummy"></div>
</div>
JS:
$().ready(function()
{
$('#about').hide();
$('#subscribe').hide();
$('#contact').hide();
$('#dummy').hide();
$('.home').click(function() {
var id = $(this).html().toLowerCase();
if ($('.current').length >0) {
if($('.current')[0].id.toLowerCase() != id)
{
$('.current').hide();
$('.current').removeClass('current');
$('#'+id).addClass('current');
$('#'+id).show();
}
else
{
$('.current').hide();
$('.current').removeClass('current');
$('#dummy').addClass('current');
}
}
});
});
Just replace the .hide()'s and .shows()'s with fades in and out.

Categories