I'm trying to get 10 elements to appear when the user clicks one of five links.
I will only show two here to save time.
These 'appearing' elements need to be links in some way or another.
HTML - LINKS
<a class="toggler1" href="#!"
><h1 class="website-titles">A boring website</h1></a
<a class="toggler2" href="#!"
><h1 class="website-titles">Unoriginal.co.uk</h1></a
HTML - Appearing elements
<a class="mydiv1" href="main.html">
<div class="pop-up-1">
<img
class="mydiv1-bg"
src="images/pink-pop-up.png"
alt="pink pop up"
/>
<img
class="mydiv1-gif"
src="images/spinning-star.gif"
alt="animated star gif"
/>
</div>
</a>
<a class="mydiv2" href="main.html">
<div class="pop-up-2">
<img
class="mydiv2-bg"
src="images/black-pop-up.png"
alt="black pop up"
/>
<img
class="mydiv2-gif"
src="images/stars.gif"
alt="animated star background"
/>
<h1 class="mydiv2-text">
CLICK HERE TO RE-INVIGORATE YOUR WEB SURFING EXPERIENCE!!!
</h1>
</div>
JS -
This is my JS for one link, copy and pasted 2 times for convenience sake (in the real code it's 5 times for 5 links), with the elementToClick set to different classes (toggler1,toggler2... etc) within each tag. If I copy and paste this again, with another elementToShow (mydiv2 for example), this doesn't work - only one of the elements will appear
<script>
var elementToClick = document.querySelector(".toggler1");
var elementToShow = document.querySelector(".mydiv1");
if (elementToClick) {
elementToClick.addEventListener("click", showElement);
}
function showElement() {
elementToShow.classList.add("show");
}
</script>
<script>
var elementToClick = document.querySelector(".toggler2");
var elementToShow = document.querySelector(".mydiv1");
if (elementToClick) {
elementToClick.addEventListener("click", showElement);
}
function showElement() {
elementToShow.classList.add("show");
}
</script>
CSS
/* POP UP 1 */
.mydiv1 {
display: none;
}
.mydiv1.show {
display: block;
}
/* POP UP 2 */
.mydiv2 {
display: none;
}
.mydiv2.show {
display: block;
}
Thank you for looking at this mess, I am very new to Javascript and I'm sure I'm making this unnecessarily complicated for myself. If anyone can tell me how to get this working it would be greatly appreciated! Thanks!
In your Javascript code, in the showElement, use elementToShow.classList.toggle("show"); instead of elementToShow.classList.add("show");.
var elementToClick = document.querySelector(".toggler1");
var elementToShow = document.querySelector(".mydiv1");
if (elementToClick) {
elementToClick.addEventListener("click", showElement);
}
function showElement() {
elementToShow.classList.toggle("show");
}
var elementToClick = document.querySelector(".toggler2");
var elementToShow = document.querySelector(".mydiv1");
if (elementToClick) {
elementToClick.addEventListener("click", showElement);
}
function showElement() {
elementToShow.classList.toggle("show");
}
/* POP UP 1 */
.mydiv1 {
display: none;
}
.mydiv1.show {
display: block;
}
/* POP UP 2 */
.mydiv2 {
display: none;
}
.mydiv2.show {
display: block;
}
<a class="toggler1" href="#!"
><h1 class="website-titles">A boring website</h1>
</a>
<a class="toggler2" href="#!">
<h1 class="website-titles">Unoriginal.co.uk</h1>
</a>
<a class="mydiv1" href="main.html">
<div class="pop-up-1">
<img
class="mydiv1-bg"
src="images/pink-pop-up.png"
alt="pink pop up"
/>
<img
class="mydiv1-gif"
src="images/spinning-star.gif"
alt="animated star gif"
/>
</div>
</a>
<a class="mydiv2" href="main.html">
<div class="pop-up-2">
<img
class="mydiv2-bg"
src="images/black-pop-up.png"
alt="black pop up"
/>
<img
class="mydiv2-gif"
src="images/stars.gif"
alt="animated star background"
/>
<h1 class="mydiv2-text">
CLICK HERE TO RE-INVIGORATE YOUR WEB SURFING EXPERIENCE!!!
</h1>
</div>
</a>
Wrap all the elements you want to show in a div tag. For example:
<div id="elementToShow">
<a class="mydiv1" href="main.html">
.....
</div>
In your js select that enclosing element
var elementToShow = document.querySelector("#elementToShow");
The problem is in JavaScript part. You have multiple script tags, each of which have elementToClick and elementToShow. When you define elementToClick in the second (or any other) script tag, the previous ones are being overwritten. You only have one elementToClick and one elementToShow, instead of five. The same is true for all the other variables and functions (showElement).
Another piece of advice, try to use reusable code and try to never copy and paste code, like you did here. You can define one function:
function showElement(elementToShow) {
elementToShow.classList.toggle("show");
}
Then you can call this function for each of five elements:
let elements = [
{toggler: 'toggler1', div: 'div1'},
{toggler: 'toggler2', div: 'div2'},
...
];
for (let el of elements) {
let toggler = document.querySelector(`.${el.toggler}`);
let div = document.querySelector(`.${el.div}`);
toggler.addEventListener('click', () => showElement(div)); // add a click listener with a corresponding div
}
Hope this helps!
Related
I need make a simple JS popup to view specific content of each link (team stats). For that I've got basic HTML set up which should popup mentioned content.
<!-- Start Team-Players -->
<div class="team-players">
<div class="player-profile">
<img data-js="open" src="img/team-ico/team-srsne.jpg" alt="" class="thumbnail">
<span class="number">#1</span>
<span class="name">HK Sršňe Košice</span>
</div>
<div class="player-profile">
<img data-js="open" src="img/team-ico/team-kvp.jpg" alt="" class="thumbnail">
<span class="number">#2</span>
<span class="name">HK KVP Represent</span>
</div>
<div class="player-profile">
<img data-js="open" src="img/team-ico/team-warriors.jpg" alt="" class="thumbnail" >
<span class="number">#3</span>
<span class="name">HK Spartan Warriors</span>
</div>
etc...
at the end there is popup opening code:
<div class="container">
<button data-js="open">Open popup</button>
<div class="popup">
<h2>$team_name (team name, which was selected for links above should be displayed)</h2>
<button name="close">Close popup</button>
JavaScript code:
function popupOpenClose(popup) {
/* Add div inside popup for layout if one doesn't exist */
if ($(".wrapper").length == 0){
$(popup).wrapInner("<div class='wrapper'></div>");
}
/* Open popup */
$(popup).show().this;
/* Close popup if user clicks on background */
$(popup).click(function(e) {
if ( e.target == this ) {
if ($(popup).is(':visible')) {
$(popup).hide();
}
}
});
/* Close popup and remove errors if user clicks on cancel or close buttons */
$(popup).find("button[name=close]").on("click", function() {
if ($(".formElementError").is(':visible')) {
$(".formElementError").remove();
}
$(popup).hide();
});
}
$(document).ready(function () {
$("[data-js=open]").on("click", function() {
popupOpenClose($(".popup"));
});
});
Could someone help me and advise how can I sort those links to open popup window related to each link? Maybe sort it with some ID or so?
Appreciate
I have 2 solutions:
in html create hidden popups for all teams with id="popup-team-1", and in your link add additional attribute <a data-id="1".. , in javascript do something like this:
var id = $(this).attr("data-id");
$("#popup-team-"+id).show();
load content of popup from server
$.get(url).done(function (content) {
$(".popup").html(content).show();
})
I can't adjust my text to be center aligned. I tried to put css code in onmouseover="hover('')" but it doesn't work. What is the get around for this?
Middle circle with id="content" that changes the tag on hover
<div id="circle">
<p id="content">
<b><span>Services</span></b>
</p>
</div>
JS Code that I included in the html tag to change content on hover
<a href="">
<div onmouseover="hover('<b>BPO</b>')" onmouseout="hover('<b>Services</b>')" class="scaling" id="circle-2">
<img src="/static/img/2.png" onmouseover="this.src='/static/img/2b.png'" onmouseout="this.src='/static/img/2.png'" style="margin-top:5px;" width=100px/>
</div>
</a>
<a href="">
<div onmouseover="hover('<b>Web Development</b>')" onmouseout="hover('<b>Services</b>')" class="scaling" id="circle-3">
<img src="/static/img/4.png" onmouseover="this.src='/static/img/4b.png'" onmouseout="this.src='/static/img/4.png'" style="margin-top:5px;" width=100px/>
</div>
</a>
JS Code that changes the content of the <p> tag
function hover(description) {
console.log(description);
document.getElementById('content').innerHTML = description;
}
everything is working properly but I can't adjust the text to be in the center regard less of the <p> tag length .
The main question is how do i add css code in onmouseover="hover('')"
What i want it to look like
what it looks like
Your code really needed a lot of cleaning up.
You should separate the HTML, CSS and JavaScript. After doing this, debugging is SO much easier and the code is much simpler to follow.
In addition, you had a great deal of duplication in your code. Again, using CSS and JavaScript can remove that redundancy. For example, styling is done with CSS, not HTML. Tags like <b> are deprecated and should no longer be used. By creating CSS styles that incorporate font-weight:bold and applying those styles properly, we can get rid of all the <b> and </b> tags.
// Get all DOM references:
var content = document.getElementById('content');
var cir2 = document.getElementById("circle-2");
var cir3 = document.getElementById("circle-3");
var img1 = document.getElementById("img1");
var img2 = document.getElementById("img2");
// Attach event handlers:
cir2.addEventListener("mouseover", function(){ hover('BPO') });
cir2.addEventListener("mouseout", function(){ hover('Services') });
cir3.addEventListener("mouseover", function(){ hover('Web Development') });
cir3.addEventListener("mouseout", function(){ hover('Services') });
img1.addEventListener("mouseover", function(e){ changeSource(e,'http://plumseattle.com/wp-content/uploads/2016/01/linkedin-logo.jpg') });
img1.addEventListener("mouseout", function(e){ changeSource(e, 'https://cdn3.iconfinder.com/data/icons/free-social-icons/67/facebook_circle_color-256.png') });
img2.addEventListener("mouseover", function(e){ changeSource(e, 'http://seeklogo.com/images/S/snapchat-logo-2D9C3E7ADA-seeklogo.com.png') });
img2.addEventListener("mouseout", function(e){ changeSource(e, 'https://www.seeklogo.net/wp-content/uploads/2011/06/Twitter-icon-vector-400x400.png') });
function hover(description) {
//console.log(description);
content.textContent = description;
}
function changeSource(evt, source){
evt.target.src = source;
}
content > span { font-weight: bold;}
.scaling { font-weight:bold; }
.img { margin-top:5px;width:100px; }
<div id="circle">
<p id="content">
<span>Services</span>
</p>
</div>
<a href="">
<div class="scaling" id="circle-2">
<img id="img1"
src="https://cdn3.iconfinder.com/data/icons/free-social-icons/67/facebook_circle_color-256.png"
class="img">
</div>
</a>
<a href="">
<div class="scaling" id="circle-3">
<img id="img2"
src="https://www.seeklogo.net/wp-content/uploads/2011/06/Twitter-icon-vector-400x400.png"
class="img">
</div>
</a>
Typically, if you want some element to listen to "mouseover" event, the best way to go is to use EventTarget#addEventListener. Just like this:
const node = document.getElementById('hover');
node.addEventListener('mouseover', () => {
node.innerText = `Last time mouseover'd at ${new Date()}.`;
});
So, now, you need to update children of #content and src attribute of an image under mouse cursor.
The HTML would look like this:
<p id="content">
Services
</p>
<a href="">
<div class="scaling" id="circle-2">
<img src="/static/img/2.png" />
</div>
</a>
<a href="">
<div class="scaling" id="circle-3">
<img src="/static/img/2.png" />
</div>
</a>
while JS code would look like this:
const content = document.getElementById('content');
const circle2 = document.getElementById('circle-2');
const circle3 = document.getElementById('circle-3');
circle2.addEventListener('mouseover', () => {
circle2.children[0].src = '/static/img/2b.png';
content.innerText = 'BPO';
});
circle2.addEventListener('mouseout', () => {
circle2.children[0].src = '/static/img/2.png';
content.innerText = 'Services';
});
circle3.addEventListener('mouseover', () => {
circle3.children[0].src = '/static/img/4b.png'
content.innerText = 'Web Development';
});
circle3.addEventListener('mouseout', () => {
circle3.children[0].src = '/static/img/4.png'
content.innerText = 'Services';
});
(check out this fiddle).
I know very little about JavaScript at all, but I'm looking for a solution to a simple code that I'd like to use. I'm not trying to execute any slides or fades, just a simple slideshow that switches from one image to the next. I want the slideshow to play through just once, and then stop on the last image in the sequence. Any help would be greatly appreciated!
$("#slideshow > div:gt(0)").hide();
setInterval(function() {
$('#slideshow > div:first')
.next()
.end()
.appendTo('#slideshow');
}, 3000);
As I said, it's a very simple code. The first GIF runs only once, the second GIF loops. I would like the slideshow to stop on the looping GIF. I'm wondering if the '3000' (which I know corresponds to the length of each slide) can be changed to accomplish what I'm looking for. Or else adding a stop function... which I don't know how to write.
<div id="slideshow">
<div>
<img src="https://31.media.tumblr.com/e2c4bbaeb781a3b834cd09549595393f/
tumblr_noy3q3l1dy1uwyyx9o2_1280.gif">
</div>
<div>
<img src="https://33.media.tumblr.com/1d6495399687801067d62c83c4218644/
tumblr_noy3q3l1dy1uwyyx9o1_1280.gif">
</div>
</div>
Ok I have made this with the objective of being as clear and simple for you to understand as possible, (since you new to js...)
JS/Jquery:
$(function () {
setTimeout(playSlideShow, 3000);
function playSlideShow() {
var currImgContainer = $('.showImg');
if (!$(currImgContainer).hasClass('lastImg')) {
$('.showImg').removeClass('showImg').next().addClass('showImg');
setTimeout(playSlideShow, 3000);
}
}
});
So here we find the imgContainer(div) with the class "showImg", then using chaining, we remove the class and add it to the next imgContainer(div). Therefore toggling the CSS to show/hide the image until it finds the div that has the class "lastImg".
CSS:
.slideShow > div:not(.showImg) {
display: none;
}
.showImg {
display: block;
width: 400px;
height: 400px;
}
HTML:
<div class="slideShow" id="slideshow">
<div class="showImg">
<img src="Images/img1.png" alt="" />
</div>
<div>
<img src="Images/img2.png" alt="" />
</div>
<div>
<img src="Images/img3.png" alt="" />
</div>
<div class="lastImg">
<img src="Images/img4.png" alt="" />
</div>
</div>
This way you can have as many images as you want, just make sure the last div has class "lastImg" and the first one has the class "showImg".
Here is a fiddle
Hope it helps...
Try this:
var intervalID = null;
var iterator = 0;
var intervalDuration = 3000;
var slideshow = $('#slideshow');
var divs = slideshow.find('div');
//divs.filter(':gt(0)').hide();
divs.eq(iterator).show();
intervalID = setInterval(function(){
divs.eq(iterator).hide();
iterator += 1;
if (iterator === divs.length - 1) { clearInterval(intervalID); }
divs.eq(iterator).show();
}, intervalDuration);
#slideshow > div { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="slideshow">
<div>
<img src="https://dl.dropboxusercontent.com/u/45891870/Experiments/Codepen/PIXI/0.4/images/JS.jpg" />
</div>
<div>
<img src="https://dl.dropboxusercontent.com/u/45891870/Experiments/Codepen/PIXI/0.4/images/PIXI.jpg" />
</div>
<div>
<img src="https://dl.dropboxusercontent.com/u/45891870/Experiments/Codepen/PIXI/0.4/images/JS.jpg" />
</div>
</div>
The HTML structure is same as yours but the only thing that I have changed are the image sources (tumbler images weren't loading for me). But JavaScript has been changed completely.
Add as many DIVs as you like in your HTML to test it out. Hope it helps.
Update #1:
Added CSS to hide the divs by default.
Increased the intervalDuration to 3000. Just to make sure there is ample time for the images to be loaded.
Commented the filter line of JS.
Added another JS line right below the previous filter line.
This update should also load your GIF only when it is needed to appear, hence will not be running in the background.
Let me if this works.
var popup;
jQuery(document).ready(function(){
jQuery(window).bind('load',windowLoadComplete);
});
function windowLoadComplete() {
var settings = new Object();
popup = new SSKpopup(settings);
popup.createPopup();
jQuery('a').each(function(n){
if(jQuery(this).attr('href').indexOf("popup#")>-1) {
jQuery(jQuery(this).attr('href').split("popup#")[1]).hide();
jQuery(this).click(function(e) {
e.preventDefault();
popup.loadContent(jQuery(jQuery(this).attr('href').split("popup#")[1]));
});
}
});
}
I have that piece of code that is to create a popup containing pictures, information just like like http://jqueryui.com/demos/tabs/ and in my html code I create the popup as follows,
<a class="popup" href="/main/popup##hulk">Key Speakers</a>
<br>
Chairman
</p>
<div id="hulk" style="width: 450px; display: none;">
<img class="popup_img" border="0" alt="" src="/main/images/speaker.jpg">
<p>Content descriping the speakers</p
</div>
When I use firebug over the href I see the address different from normal location and if I insert into its as index.php/main/popup#$hulk to be same as every other links and click it then, the page direct me to localhost/xampp/. Of course no popup was displayed.
I have created an HTML file which uses java script to display images randomly displayed in 3 div tags. On click the images move left or right. It works fine until I use single slideshow in the page, but creates problem when I try multiple slideshows on the same page.
Here is the code for one slide show :
**<script>
currentIndx = 2;
MyImages=new Array();
MyImages[0]='1images2.jpeg';
MyImages[1]='1images3.jpeg';
MyImages[2]='1images4.jpeg';
MyImages[3]='artwork.jpg';
MyImages[4]='1images5.jpeg';
imagesPreloaded = new Array(4)
for (var i = 0; i < MyImages.length ; i++)
{
imagesPreloaded[i] = new Image(120,120)
imagesPreloaded[i].src=MyImages[i]
}
/* we create the functions to go forward and go back */
function Nexter()
{
if (currentIndx<MyImages.length-1){
alert(currentIndx);
document.leftimg.src=document.middleimg.src
document.middleimg.src=document.rightimg.src
document.rightimg.src=imagesPreloaded[++currentIndx].src
}
else {
alert("In nexter else")
currentIndx=0
document.leftimg.src = document.middleimg.src
document.middleimg.src = document.rightimg.src
document.rightimg.src = imagesPreloaded[currentIndx].src
}
writeImageNumber();
}
function Backer()
{
if (currentIndx>0)
{
--currentIndx;
alert("In Backer If");
document.rightimg.src=document.middleimg.src
document.middleimg.src=document.leftimg.src
document.leftimg.src=imagesPreloaded[currentIndx].src
}
else
{
currentIndx = MyImages.length-1
alert(MyImages.length +"else");
document.rightimg.src = document.middleimg.src
document.middleimg.src = document.leftimg.src
document.leftimg.src = imagesPreloaded[currentIndx].src
}
writeImageNumber();
}
/*###### function to reload the images and text when refresh is pressed ##### */
function setCurrentIndex()
{
currentIndx=0;
document.theImage.src=MyImages[0];
document.form1.text1.value=Messages[0];
writeImageNumber();
}
</script>
<body onload="setCurrentIndex();automaticly()">
<!-- start of form for image slide show ####################### -->
<div id ="left" style="float:left">
<a href="#" onclick="Backer()" ><img src="1images2.jpeg" width="265" height="262"
border="0" name="leftimg"></a>
</div>
<div id ="middle" style="float:left">
<a href="#" onclick=""><img src="1images3.jpeg" width="265" height="262"
border="0" name="middleimg"></a>
</div>
<div id ="right" class="compimg" style="float:left">
<a href="#" onclick="Nexter()" ><img src="1images4.jpeg"
width="265" height="262" alt="" border="0"name="rightimg"></a>
</div>
<!-- end of form for image slide show ####################### -->**
Any suggestions...
You haven't wrapped your script in any javascript class(object) so all variables you are using have global scope(page level). I guess your variables are over written if you try to use it multiple time.
You can get better answer if you post HTML markup of how you are trying to create multiple slideshow in single page...