Link or button sets a variable, then calls the script - javascript

I have a script that plays a video in a Modal when a thumbnail gets clicked. This only works with the first video mentioned in the html, so I'm trying to use js to grab the particular video whos thumbnail is clicked on.
I have set up a variable in the js called vidcode, and gave it a value of the first video's address (rLdpnu2dDUY) or whatever it's called. I then set up a value 'start' for the link part before, and 'end' for the link part after. Now I have "showVideo = start + vidcode + end" and then innerHTML = showVideo, which works no problems.
So far the injection part works. My problem now is passing the address of the clicked thumbnail into the vidcode variable to play the corresponding video. I have looked on SO, w3, and Google. I have 6 different tries and none work fully.
I can create a link which
- Sets the variable, but then does not call the script.
- Calls the script but does not pass on the variable.
- Click one thumb to set the variable then another thumb to call the script. That one will then work but it's an extra step. At least with this one I know that the variable is being set..
<!--== Standard button but requires var vidcode to be preset in the Modal script ==-->
<img src="https://img.youtube.com/vi/rLdpnu2dDUY/hqdefault.jpg">
<!--== Add onClick to trigger a mini-script which sets the var vidcode early ==-->
<script>function hDSansxhArU(){var vidcode = 'hDSansxhArU';}</script>
<!--== Adding the javascript directly to the link code, yet it does not trigger the Modal script ===-->
<!--== Adding the javascript directly to the link code, to trigger a mini-script, to then call the modal ===-->
<script>function buttt(){var vidcode = 'duBjWlIzpzQ'; modalviewer();}</script>
<!--== Use the video's code as an id, then calling that id immediately and setting it to var vidcode ==-->
<script>
document.getElementById('hDSansxhArU').onclick = function() {
var vidcode = 'hDSansxhArU';
modalviewer()
};
</script>
Spots are commented out when trying something else
function modalviewer(){ //This function usually isn't here
var start = '<iframe width="840" height="472" src="https://www.youtube.com/embed/';
var end = '" frameborder="0" encrypted-media></iframe>';
//var showVideo = start + vidcode + end;
// This part works fine when vidcode gets a value
document.getElementById("button").addEventListener("click", function() {
document.querySelector(".theVideo").innerHTML = showVideo;
document.querySelector(".bg-modal").style.display = "flex";
});
document.querySelector(".bg-modal").addEventListener("click", function() { //.bg-modal to make the surrounding clickable
document.querySelector(".bg-modal").style.display = "none";
document.querySelector(".theVideo").innerHTML = "";
});
};
Expected results:
Click a link and have either
- set that address to variable 'vidcode', or
- set the address gobbledegook to 'vidcode' from here
and either have the modal script in a separate js file or at the bottom of the page.
As a code-newbie, I'm proud to have figured it out so far (with previous help from SO), it just frustrates me that I can only get half of this to work at a time :/.

#CTOverton provided what was needed, although everyone else and in Stop/Pause video when Modal is closed (not using $ sign) contributed with everything that they got me to look up as well. #Phoenix1355 actually started me on the right path despite me not posting any code at all, in turn leading me to learn so much in very little about Javascript and HTML.
This has been plaguing me for at least a week (I've lost track of time making this website), researching, getting other setups, trying overly-complicated setups, being told it can only be done by paying for a hosting plan or having to use Wordpress.. And this Console.log output, sooo helpful omg. Thank you everyone who contributed!
Here is the finished code:
<html>
<head>
<link href="http://www.jolanxbl.ca/snips/modal.css" rel="stylesheet" />
</head>
<body>
<center>
<br><br><br><br><br>
<!--List of videos-->
<img data-vidcode="rLdpnu2dDUY" src="https://img.youtube.com/vi/rLdpnu2dDUY/hqdefault.jpg" width="200px">
<img data-vidcode="hDSansxhArU" src="https://img.youtube.com/vi/hDSansxhArU/hqdefault.jpg" width="200px">
<img data-vidcode="duBjWlIzpzQ" src="https://img.youtube.com/vi/duBjWlIzpzQ/hqdefault.jpg" width="200px">
</center>
<!-- Modal Section 1 -->
<div class="bg-modal">
<div class="modal-content">
<div class="close">+</div>
<div class="theVideo">
<iframe width="840" height="472" src="https://www.youtube.com/embed/rLdpnu2dDUY" frameborder="0" encrypted-media; picture-in-picture allowfullscreen></iframe>
</div>
</div>
</div>
<script>
let vidcode = 'rLdpnu2dDUY';
// Get all elements with classname 'thumbnail'
let thumbnails = document.getElementsByClassName('thumbnail');
// Loop for every element with class
Array.from(thumbnails).forEach(function(element) {
element.addEventListener('click', thumbnailClicked);
});
function thumbnailClicked(event) {
// Event is mouse click event
// target is the img (as that is what you click on)
// dataset is the data attributes of img
vidcode = event.target.dataset.vidcode;
console.log('vidcode: ', vidcode)
//document.querySelector(".gridContainer").addEventListener("click", function() {
document.querySelector(".theVideo").innerHTML = '<iframe width="840" height="472" src="https://www.youtube.com/embed/' + vidcode + '" frameborder="0" encrypted-media></iframe>';
document.querySelector(".bg-modal").style.display = "flex";
}
document.querySelector(".bg-modal").addEventListener("click", function() { //.bg-modal to make the surrounding clickable
document.querySelector(".bg-modal").style.display = "none";
document.querySelector(".theVideo").innerHTML = "";
});
</script>
</body>
</html>

Based on your description I think you are looking for something along the lines of the "data attribute". Data attributes are custom attributes you can assign to any DOM element that contain essentially whatever you want.
In you case if you have a page with lots of thumbnails and you want a specific action to happen when you click on a specific thumbnail, your best bet is if you store that unique identifier (the video id, or are you put it vidcode) on the element you are clicking on.
This can be done like this:
<body>
<!--List of videos-->
<img data-vidcode="rLdpnu2dDUY" src="https://img.youtube.com/vi/rLdpnu2dDUY/hqdefault.jpg">
<img data-vidcode="example2" src="img2.jpg">
<img data-vidcode="example3" src="img3.jpg">
<script>
let vidcode = 'rLdpnu2dDUY';
// Get all elements with classname 'thumbnail'
let thumbnails = document.getElementsByClassName('thumbnail');
// Loop for every element with class
Array.from(thumbnails).forEach(function(element) {
element.addEventListener('click', thumbnailClicked);
});
function thumbnailClicked(event) {
// Event is mouse click event
// target is the img (as that is what you click on)
// dataset is the data attributes of img
vidcode = event.target.dataset.vidcode;
console.log('vidcode: ', vidcode)
}
</script>
</body>

Try passing the vidcode as an parameter for modalviewer function and then use the value.
function modalviewer(vidcode){
var start = '<iframe width="840" height="472" src="https://www.youtube.com/embed/';
var end = '" frameborder="0" encrypted-media></iframe>';
var showVideo = start + vidcode + end;
document.querySelector(".theVideo").innerHTML = showVideo;
};
<div class="theVideo"></div>
Click
<script>
document.getElementById('hDSansxhArU').onclick = function() {
var vidcode = 'hDSansxhArU';
modalviewer(vidcode)
};
</script>

Related

Using an attribute value to add custom links for each images in my wordpres gallery

I'm using Elementor Pro for my photography website and i want to set custom links for each image in the gallery. By default, i can only set a global link which is the same for each image so that's not great.
In fact, i want to set a custom link which will redirect the user to the shop page of the specific image.
I found some code online (thanks to elementhow !) and it's really close to what i want, but i still need to change some things. The thing is a have to manually write all the links in an array and it's not convenient (close to 100 files and growing, if i change the order, i have to reorder the links, etc).
Here's the code i currently use :
<style>.e-gallery-item{cursor: pointer;} </style>
<script>
document.addEventListener('DOMContentLoaded', function () {
var filteredImages = document.querySelectorAll('.e-gallery-item');
//Edit the links HERE
var links = [
'https://www.mywebsiteurl.com/product/product-name1/',
'https://www.mywebsiteurl.com/product/product-name2/',
'https://www.mywebsiteurl.com/product/product-name3/',
'https://www.mywebsiteurl.com/product/product-name4/',
];
var _loope = function _loope(i) {
filteredImages[i].addEventListener('click', function () {
location = links[i];
});
};
for (var i = 0; i < filteredImages.length; i++) {
_loope(i);
}
});
</script>
I would like to use an attribute value in the algorithm to generate the link automatically for each image. I have the process in my mind, but i don't know how to code this...
Here's the code of one image ,i can set what value i want in "alt".
<div class="e-gallery-image elementor-gallery-item__image e-gallery-image-loaded" data-thumbnail="......" data-width="1024" data-height="768" alt="product-name";"></div>
I would like to use the "alt" attribute to create a unique url for each file, with this format :
'https://www......com/product/product-name/'
"product-name' will take the value of the "alt" attribute of each image.
I tried to change this part of the code (replace "links[i]" by trying to get the attribute value using filteredImages[i].getAttributes) but without success...
var _loope = function _loope(i) {
filteredImages[i].addEventListener('click', function () {
location = links[i];
});
};
Can someone give me some tips about how to do that ? I spend 2 years without coding so i'm a bit rusty...
I think this does what you'd like it to, as you have already done you can cycle through each image link using a class.
You can get the value of alt using the .attr() function and then replace the href value of the link.
DEMO
// Cycle through each image using common class
$(".e-gallery-image").each( function() {
// Get value of 'alt' for clicked item
alt = $(this).attr("alt");
// Update href value
$(this).attr("href", "https://www.mywebsiteurl.com/product/" + alt );
});
// Prove that its worked
$(".e-gallery-image").click( function() {
// Confirm all is correct
console.log($(this).attr("href"));
// Assign url to window
location.href = $(this).attr("href");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="e-gallery-image" href="test.com" alt="product1">Product 1</div>
<div class="e-gallery-image" href="test.com" alt="product2">Product 2</div>
<div class="e-gallery-image" href="test.com" alt="product3">Product 3</div>
<div class="e-gallery-image" href="test.com" alt="product4">Product 4</div>
<div class="e-gallery-image" href="test.com" alt="product5">Product 5</div>
In fact it was really simple. I tried to target a parent element and it worked ! If anyone is interested, here's the code i use :
document.addEventListener('DOMContentLoaded', function () {
var filteredImages = document.querySelectorAll('YOUR_SELECTOR');
var _loope = function _loope(i) {
filteredImages[i].addEventListener('click', function() {
location = "YOUR_WEBSITE_URL" + filteredImages[i].querySelector("YOUR_SELECTOR").getAttribute("alt");
});
};
for (var i = 0; i < filteredImages.length; i++) {
_loope(i);
}
});

Wrong increment and decrement in javascript

As it's understandable from the code, I'm trying to create a simple img gallery.
I'm currently facing a calculation problem; if you run the snippet performing these actions you'll see what's wrong in the console log:
clicking on an img you'll get the id of the current clicked id
if you click next the first number it prints out is the same of the clicked id
but if you click now prev you'll see that actually the value was correct 'cause it prints the incremented number and you need to clicks to decrement
if you click now on another img you'll get the id of the new clicked div
but if you click now prev or next it performs the increment or decrement two times and it seems as the previous variable $ph_id is not overwritten by the new id
Can someone please explain me where the problem comes from? 'Cause I thought the code was written right but apparently I'm missing something.
[EDIT] I put the $('#next').click(function () and the $('#prev').click(function () outside of the $('.venus-div').click(function () and the problem at points 4. and 5. are now solved
$(document).ready(function () {
$('.venus-div').click(function () {
$this = $(this);
$ph_id = $this.attr('id');
console.log('Current id: ' + $ph_id);
});
$('#next').click(function () {
$next_id = $ph_id++;
console.log('Next id: ' + $next_id);
});
$('#prev').click(function () {
$prev_id = $ph_id--;
console.log('Prev id: ' + $prev_id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="venus-div" id="1" data-image="../img/bv.jpg">
<img src="../img/thumb/bv_thumb.jpg" class="venus-thumb">
</div>
<div class="venus-div" id="2" data-image="../img/islamuj.jpg">
<img src="../img/thumb/islamuj_thumb.jpg" class="venus-thumb">
</div>
<div class="venus-div" id="3" data-image="../img/vertical.jpg">
<img src="../img/thumb/vertical_thumb.jpg" class="venus-thumb">
</div>
<div class="venus-div" id="4" data-image="../img/pano.jpg">
<img src="../img/thumb/pano_thumb.jpg" class="venus-thumb">
</div>
<p id="prev">BACK</p>
<p id="next">NEXT</p>
$next_id = $ph_id++; sets $next_id to the current value of $ph_id and then increments $ph_id by one. If you want the increment to happen first, you can place the ++ before the variable like so:
$next_id = ++$ph_id;
With this, $next_id will be equal to the incremented $ph_id.
The same applies to --:
$prev_id = --$ph_id;
I think its because you are creating and binding every click a new click event in next and prev, and its triggering multiple times due to this multiple binding. You can either off these events or bind them outside the venus-div click function (making ph_id, next_id and prev_id global vars inside document ready.
I cant write coding from mobile, if you need i'll update it later :)

Unable to get script to send and html to receive and show text via 'onclick'

I am just teaching myself coding and am stuck, please go easy on me as I am a newbie...... I would appreciate any help with my website...
I have created this code which works fine.....
<script type="text/javascript">
function swapImage3(id,primary,secondary,thirdly,fourthly,fifthly) {
src=document.getElementById(id).src;
if (src.match(primary)) {
document.getElementById(id).src=secondary;
greeting='Click two';
} else if (src.match(secondary)) {
document.getElementById(id).src=thirdly;
greeting='Click three';
} else if (src.match(thirdly)) {
document.getElementById(id).src=fourthly;
greeting='Click four';
} else if (src.match(fourthly)) {
document.getElementById(id).src=fifthly;
greeting='Click five';
} else if (src.match(fifthly)) {
document.getElementById(id).src=primary;
greeting='Click one';
}
}
</script>
<body>
<div id="carousel_containerSL">
<div class="text14">
<div id="slider3">
<div class="wrap">
<img id="three"
draggable="false"
src="images/COL1.jpg"
onclick="swapImage3('three', 'images/COL2.jpg', 'images/COL3.jpg',
'images/COL4.jpg', 'images/COL5.jpg',
'images/COL1.jpg')"
onmouseout="this.src='images/COL1.jpg'"
onclick="swapImage3(
<h3 class="captz">
<script>
document.write ("greeting")
</script>
</h3>
Except...
...although my pictures rotate fine using 'onclick' and revert to the original onmousout, I have a total brain-fog regarding getting the text in the:
document.write ("greeting")
position at the bottom underneath each picture to rotate with the same onclicks... I am attempting to get it to read from variable:
greeting="Click"
in the top script... but I fear the is my mistake??...
So to clarify, I wish to change some text and get it to rotate with the pictures... I am running before I can walk, but everything else seems to work on my site except this...
Any help??? Please??
Don't use document.write()...ever. It is a very old way of adding content to a document while the document is being built. Using it after the document is built, which is what you are trying to do, will cause the existing document to be thrown away and an entirely new one to be written. Instead use innerHTML or textContent to inject the content into the document (a.k.a. the "DOM").
Here's an example of how to structure the code with your click event working. I'm not sure what you were after with your mouseout function since it simply sets the image source to the same value that it already had.
// When the document is loaded run the function called "init"
window.addEventListener("DOMContentLoaded", init);
function init(){
// This function will run as soon as the document is loaded and ready for interaction
// Set up variables that will need to be used throughout the function
// These variables will point to the HTML objects you need to interact with
var img = document.getElementById("three");
var h3 = document.querySelector("h3.captz");
// Set up event handling functions:
img.addEventListener("click", function(e){
swapImage3(e.target, 'https://cdn0.iconfinder.com/data/icons/social-flat-rounded-rects/512/facebook-256.png', 'https://cdn0.iconfinder.com/data/icons/social-flat-rounded-rects/512/facebook-256.png',
'http://blueblots.com/wp-content/uploads/2010/09/high-details-social-facebook-icon.jpg', 'http://wfarm4.dataknet.com/static/resources/icons/set113/badaf4a8.png', 'http://www.seaicons.com/wp-content/uploads/2016/03/Facebook-icon-26.png');
});
img.addEventListener("mouseout", function(e){
e.target.src='http://www.seaicons.com/wp-content/uploads/2016/03/Facebook-icon-26.png'
});
function swapImage3(obj,primary,secondary,thirdly,fourthly,fifthly) {
console.log(obj.src,primary,secondary,thirdly,fourthly,fifthly)
var greeting = "";
switch(obj.src){
case primary:
greeting = 'two';
break;
case secondary:
greeting = 'three';
break;
case thirdly:
greeting = 'four';
break;
case fourthly:
greeting = 'five';
break;
case fifthly:
greeting = 'one';
break;
}
h3.textContent = "Click " + greeting;
}
}
img {width:10%;}
<div id="carousel_containerSL">
<div class="text14">
<div id="slider3">
<div class="wrap">
<h3 class="captz"></h3>
<img id="three" draggable="false" src="http://www.seaicons.com/wp-content/uploads/2016/03/Facebook-icon-26.png">

Javascript move multiple elements to separate div's and back

There are 3 videos, placed in 3 separate div's.
There also are 3 separate div's, but in other position of a page (lets say contA and contB and contC).
I want that if I click on the video1, then video2 and video3 goes to contA and contB, and video1 goes to contC.
If I click video1 again, all videos go back to their original position.
If I click on video2 (while its in contA), then video1 goes to contA, video3 goes to contB, video2 goes to contC.
I have prepared a jsbin demo:
Jsbin DEMO
Anyone could help? Appreciated!
EDIT: (Added a code as requested)
HTML:
<div id="vid1">
<video id="Video1" class="videos">
<source src="http://www.craftymind.com/factory/html5video/BigBuckBunny_640x360.mp4" type="video/mp4"></source>
HTML5 Video is required for this example.
</video>
</div>
<div id="vid2">
<video id="Video2" class="videos">
<source src="http://www.craftymind.com/factory/html5video/BigBuckBunny_640x360.mp4" type="video/mp4"></source>
HTML5 Video is required for this example.
</video>
</div>
<div id="vid3">
<video id="Video3" class="videos">
<source src="http://www.craftymind.com/factory/html5video/BigBuckBunny_640x360.mp4" type="video/mp4"></source>
HTML5 Video is required for this example.
</video>
</div>
<div id="contA"><br>first container<br></div>
<div id="contB"><br>second container<br></div>
<div id="contC"><br>third container<br></div>
JavaScript:
$(window).load(function()
{
//add event for all videos
$('.videos').click(videoClicked);
function videoClicked(e)
{
//get a referance to the video clicked
var sender = e.target;
//get all the videos
var $videos = $('.videos');
$videos.appendTo('#contA');
$videos.appendTo('#contB'); //but I need each video to be put to different div: #contA, #contB...
$videos.not(sender).appendTo('#contC'); //if I put the clicked video into this container, it does not go back to original one.
}
});
Think this is what you're looking for, but it's based on the naming convention used in the example. I also took the liberty of renaming contA/contB and contC to cont1, cont2 and cont3, because it's easier to manipulate.
JSBin demo
//remember last video clicked (you could check last container instead)
var lastclicked;
function videoClicked(e)
{
//get a reference to the video clicked
var sender = e.target;
//get all the videos
var $videos = $('.videos');
if(sender==lastclicked){
//reset to original positions
$.each($videos,function(){
var ind = this.id.substring(this.id.length-1); //based on the video + number naming convention
$(this).appendTo('#vid' + ind);
});
lastclicked = null;
return;
}
lastclicked= sender;
var i = 1;
//place all non clicked videos in cont1/cont2/etc
$.each($videos.not(sender),function()
{
$(this).appendTo('#cont' + i++ );
});
//place the clicked video in the last container
$(sender).appendTo('#cont' + i ); //always cont3 with fixed divs, but this is dynamic in case you add more
}
});
I will edit this answer as the desired results become more clear but i think i can give you some info to get you going in the right direction.
the section of code "but i need each video to be put to a diff cont"
I would leverage a data attribute and let each control keep track of itself.
$video.each(function()
{
var targetdiv = $(this).data('origonal-div');
$(targetdiv.ToString()).append(this);
//optionally update the data value to keep track of the next location to append to.
}
if you need more info post some questions with an update on the jsbin so i can see where you are having trouble.
Cheers

HTML5 Audio Tag Changing Src when finished. jQuery

I have created a audio element with a ul. In the ul is list items which are linked to different songs. I have gotten the song to change when the item is clicked and it all works however i would like the song to also change when the current playing song finishes. Below is my html and js.
HTML:
<div id="mp3_player">
<div id="audio_box">
<audio id="audioPlayer" preload="auto" src="" controls="controls"></audio>
</div>
</div>
<ul id="songSelector">
<li>song1</li>
<li>song2</li>
<li>song3</li>
<li>song4</li>
</ul>
The source doesn't have a value becasuse it is added in another part of my script.
JS:
$(audio).bind('ended', function() {
var testing = $('#songSelector').next().attr('href');
alert(testing);
})
The alert returns undefined when the song finished when it should return the link on the next li element. I just cant figure out what i am doing wrong.
Thanks in advanced.
Right now, $('#songSelector').next() is going to whatever is after #songSelector in the dom. You probably need to keep track of which one is "current" in another variable.
var currentSong = $('#songSelector').find('a:first');
$(audio).bind('ended', function() {
var next = currentSong.next();
if ( next.length ) {
currentSong = next;
} else {
/* uncomment this if you want it to loop back to the beginning */
// currentSong = $('#songSelector').find('a:first');
}
var testing = currentSong.attr('href');
alert(testing);
});
Then you just need to update currentSong in your click handler as well.

Categories

Resources