I try to change the background of a div onclick and preserved it with a cookie. Here is my code. Firstly I can't realize if my cookie has been set and secondly if I can change the background with the value of the cookie.
Can anyone help with an idea?
<div class="container">
<div class="col-md-6">
<div class="one"><a id="1" onClick="addcookie()" href="#">Fisrt Link</a></div>
</div>
<div class="col-md-6">
<div class="two"><a id="2" onClick="addcookie()" href="#">Second Link</a></div>
</div>
</div>
<script src=js/jquery-1.11.1.js></script>
<script src="js/jquery.cookie.js"></script>
<script>
var cookieName = 'cookie1';
function addcookie(){
var date = new Date();
var minutes = 5;
date.setTime(date.getTime() + (minutes * 60 * 1000));
var idi = getDocumentById(this.id);
var cookieValue = "http://path to image/image"+idi+".png";
$.cookie(cookieName, cookieValue, { expires: date });
$('.one').css('background', $.cookie('cookieName'));
}
</script>
<script src=js/bootstrap.js></script>
</body>
Other than what #George already pointed out in a comment (replace getDocumentById() - non-existent native function - with document.getElementById()), you'll also have to make sure that you're adding the image URL is coded properly, os instead of...
$('.one').css('background', $.cookie('cookieName'));
...do this...
$('.one').css('background', 'url("' + $.cookie(cookieName) + '")');
This is the proper CSS syntax for including background URL's is not...
background:http://path to image/image.png
...but...
background:url("http://path to image/image.png");
...and because if you want to use a variable as a function's parameter, you have to omit the quotes around it, ie. $.cookie('cookieName') becomes $.cookie(cookieName).
Additionally, this.id will only return the id of the element if you pass this as a parameter of your inline function as follows:
onClick="addcookie(this)"
...then reference the same in your function like this:
function addcookie(that)
...and use it like this:
var idi = that.id;
Here is a jsfiddle where you can try this: http://jsfiddle.net/yxj8w6d0/
EDIT: With a few little modifications (remove the one and two classed divs, and add no-repeat to the background) you have a neat little way of always only adding the background to the element in question, assuming it's what you actually wanted to achieve: http://jsfiddle.net/yxj8w6d0/1/
EDIT #2: To get the images loaded if the cookie already exists, create another function that fires on document ready going through your links and checking them against the existing cookies, as follows:
$(document).ready(function() {
$('.container div a').each(function(){
if ($.cookie(this.id))
$(this).css('background', 'url("' + $.cookie(this.id) + '") no-repeat');
});
});
I updated the above fiddle accordingly. Try it by clicking the links first, then running the script again - you'll see that the links will keep their background: http://jsfiddle.net/yxj8w6d0/2/
Related
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>
I'm working on a script to simulate a page change in a Questionnaire I'm building. I figured maybe I could use a bunch of "if" statements to house all the logic but it's not working right, before I go and create separate functions I'd like to know if it's possible to put them all in one single function.
So far this is the script
function pageChange(){
var chng1 = document.getElementById("p1next");
var chng2a = document.getElementById("p2back");
var chng2b = document.getElementById("p2next");
var chng3a = document.getElementById("p3back");
var chng3b = document.getElementById("p3next");
var pg1 = document.getElementById("page01");
var pg2 = document.getElementById("page02");
var pg3 = document.getElementById("page03");
if (chng1.click){
pg1.style.display="none";
pg2.style.display="block";
}
if (chng2a.click){
pg1.style.display="block";
pg2.style.display="none";
}
the "p1next, p2back, p2next etc." are IDs I gave the buttons on the pages, which I have in DIVs that I respectively named "page01, page02, page03 etc."
Without the 2nd if statement the script works exactly how I want it, it changes the display for "page01" to none and the div for "page02" to block. When I add the second if statement it doesn't work.
The reason I want to do it like this rather than making actual pages is because I don't want the data to get lost when they load another page. Am I on the right track or do I need to create a new function for each page?
Not exactly on the right track, you should use onclick events, instead of if (x.click) like this:
var chng1 = document.getElementById("p1next");
var pg1 = document.getElementById("page01");
var pg2 = document.getElementById("page02");
// Events
chng1.onclick = function(){
pg1.style.display="none";
pg2.style.display="block";
};
This will save your function until the element is clicked and then execute that function. In your case, it is executed on page load, and at that moment the user is not clicking anything.
Why not try something like this:
HTML:
<div class="page" data-pg="1">...</div>
<div class="page" data-pg="2">...</div>
<div class="page" data-pg="3">...</div>
<input id="btnPrev" type="button" value="Prev" />
<input id="btnNext" type="button" value="Next" />
jQuery:
var pageNum = 1;
$(document).ready(function () {
$("#btnPrev").on("click", function () { ChangePage(-1); });
$("#btnNext").on("click", function () { ChangePage(1); });
ChangePage(0);
});
function ChangePage(p) {
$(".page").hide();
pageNum += p;
$(".page[data-pg='" + p + "']").show();
$("#btnPrev").removeAttr("disabled");
$("#btnNext").removeAttr("disabled");
if (pageNum === 1) $("#btnPrev").attr("disabled", "disabled");
if (pageNum === $(".page").length) $("#btnNext").attr("disabled", "disabled");
}
That way you can easily grow your number of pages without changing the script. My apologies by the way for doing this in jQuery.
Update:
Have a lot of time on my hands today and have not coded for while using vanilla Javascript. Here's the version of the code using plain js: https://jsfiddle.net/hhnbz9p2/
Here is my attempt that doesn't seem to be working:
$('container').find("[data-slider='" + one + "']").removeClass('hidden');
Here is the full function that is wrapped in a document. ready function
$("#service-icon").on('click', function(){
var $this = $(this);
event.preventDefault();
$this.addClass('ease-transition').toggleClass('active-slider-btn');
$(".page-wrapper").find("[data-slider='" + one + "']").toggleClass("hidden");
});
The error that I am getting is:
"Uncaught ReferenceError: one is not defined"
Things to check:
Is `container` a class or id? If so you'll need to add a `.` or `#` respectively
That the expression in the `.find()` function returns what you're expecting
Can you post a link to a JSFiddle or something?
I have a working example here that is similar to your situation.
HTML
<div class="container">
<div data-slider="1" class="hidden">1</div>
<div data-slider="2">2</div>
</div>
<button id="show-1">show slider 1</button>
CSS
.hidden {
display: none;
}
JavaScript
var one = "1";
$("#show-1").click(function(e){
$(".container").find("[data-slider='" + one + "']").removeClass("hidden");
});
Something like this has to work:
$('.page-wrapper').find("[data-slider='" + one + "']").removeClass('hidden');
See it working here: http://jsfiddle.net/sNp7x/2/
Maybe the data attribute is set via javascript as well, so you have to be aware of the timing?!
I have the following source:
<body>
<div class="slideshow_top">
<img class="slideshow_image" src="img/cycle/putritos.jpg">
</div>
<div class="slideshow_mid">
<img class="slideshow_image" src="img/cycle/stage.jpg">
</div>
<div class="slideshow_bot">
<img class="slideshow_image" src="img/cycle/marketing.jpg">
</div>
...
</body>
Assuming I have three generated new src values such as:
var src1="img/cycle/newimage1.jpg
var src2="img/cycle/newimage2.jpg
var src3="img/cycle/newimage3.jpg
How can I change the source values of the already existing images? I'm unsure because I know the surrounding divs of the images are uniquely named, but the class of the images themselves are shared. Is it still possible to update each source attribute with Javascript given this?
Looks like part of your question has to do with selecting images only if they are a child of a slideshow_top/mid/bot div element. There's a few ways to do this...
In jQuery, you could do this:
$('.slideshow_top img').attr('src',src1);
$('.slideshow_min img').attr('src',src2);
//etc.
That's just a simple Sizzle CSS-style selector. You can also use jQuery's .children() method, if you want:
$('.slideshow_top').children('img').attr('src',src1);
In plain old JavaScript it's a little more wordy, but you can still do it:
var slideShowTop = document.getElementsByClassName('slideshow_top'),
slideShowTopImage = slideShowTop[0].getElementsByTagName('IMG');
slideShowTopImage[0].setAttribute('src',src1);
//etc.
Note though, that getElementsByClassName isn't supported in version of IE less than 9, so you'll have to write your own little function to, say, loop through all elements by tag name and filter them by className, etc. jQuery might be the way to go on this one...
You can do something like:
var new_images = $.map([1,2,3], function(x) { return "newimage" + x + ".jpg"; })
$("img").each(function(i, x) { x.src = new_images[i]; })
var src_array=["img/cycle/newimage1.jpg","img/cycle/newimage2.jpg","img/cycle/newimage3.jpg"]
$(".slideshow_image").each(function(index){
$(this).attr("src",src_array[index])
})
Try
.each( function(index, Element) )
Iterate over a jQuery object, executing a function for each matched element.
//create array of images
var arrSrc = ['img/cycle/newimage1.jpg','mg/cycle/newimage2.jpg','img/cycle/newimage3.jpg'];
$('.slideshow_bot .slideshow_image').each(function(i, el){ //to loop through images
el.prop('src',arrSrc[i]); //set image here
});
.prop( propertyName, value )
I have problems for insert dynamic id into function of JavaScript the code:
$('#scroll-up1, #scroll-down1').bind({ ..............
In this example I need the function to take values of id I send across the function
$('#scroll-up+id, #scroll-down+id').bind({ ..............
The problem it´s the quotes as " or ' no works for me and I can´t use right for function works fine , this script let me scroll text ok but only problem with this because no let me send values right from id of function.
EDIT FOR ME FOR PUT ALL CODE : .....
PHP AND HTML CODE
<?php
$fil_comments=file("comments.txt");
for ($i=0;$i<sizeof($fil_comments);$i++)
{
$line=explode("~",$fil_comments[$i]);
if ($i%2==0)
{
$back=1;
}
else
{
$back=2;
}
?>
<li>
<div id="web_comment_<?php echo $back?>">
<div id="web_comment_name"><?php echo $line[0];?></div>
<div class="web_comment_texto" id="scroll<?php echo $i;?>"><?php echo $line[1];?></div>
<div class="web_comment_arrow" style="margin-left:260px;" id="scroll-down<?php echo $i;?>"><img src="imagenes/comments/arrow_up.png"></div>
<div class="web_comment_arrow" style="margin-left:288px;" id="scroll-up<?php echo $i;?>"><img src="imagenes/comments/arrow_down.png"></div>
</div>
</li>
<script>
scroll_diver(<?php echo $i;?>);
</script>
<?
}
?>
FUNCTION OF JAVASCRIPT CODE
<script type="text/javascript">
function scroll_diver(id)
{
$(function() {
var ele = $('#scroll'+id);
var speed = 30, scroll = 5, scrolling;
$('#scroll-up'+id).mouseenter(function() {
// Scroll the element up
scrolling = window.setInterval(function() {
ele.scrollTop( ele.scrollTop() - scroll );
}, speed);
});
$('#scroll-down'+id).mouseenter(function() {
// Scroll the element down
scrolling = window.setInterval(function() {
ele.scrollTop( ele.scrollTop() + scroll );
}, speed);
});
//var a='#scroll-up'+id;
//var b='#scroll-down'+id;
var a='#scroll-up'+id;
var b='#scroll-down'+id;
//$('a,b').bind({
//$('#scroll-up1, #scroll-down1').bind({
//$('#scroll-up'+id+',#scroll-down'+id)
/// THE PROBLEM HERE !!!
$('#scroll-up'+id+', #scroll-down '+id).bind({
click: function(e) {
// Prevent the default click action
e.preventDefault();
},
mouseleave: function() {
if (scrolling) {
window.clearInterval(scrolling);
scrolling = false;
}
}
});
});
}
</script>
Basically the problem it´s in the line of JavaScript function for send id, if you see the PHP code, I use bucle for for create scrolling tips with informations and in each I can scroll his content, for this I call function into the bucle with:
<script>
scroll_diver(<?php echo $i;?>);
</script>
But in this line no send right information for works ok, if I use out bucle for one specific id, works ok , with this works yes but scroll up and down crazy fast , and the controls no works fine.
Then you need to look at something like this:
$('#scroll-up' + id + ', #scroll-down' + id).bind({ ..............
As a commentor mentioned, jQuery selectors are simply strings. You can put them together as you see fit. In this case, I'm concatenating the id (which for simplest examples, I'm assuming is a number or other unique identifier) to the #scroll-up selector, so if your id was "1", you would end up with a string, effectively, that looks like:
'#scroll-up1, #scroll-down1'
after the string concatenation occurs.
Also, it might be worth noting that you'd probably get better bang for your buck if you simply gave both objects the same class, then inside your binding function, work out which item called and perform your scrolling appropriately.
So, if you had:
<div class="container">
<div id="scroll-up1" class="scroller"><!-- and code --></div>
<div id="scroll-down1" class="scroller"><!-- and code --></div>
</div>
then your javascript could look like this, avoiding the need for concatenation:
$('.container').on("mouseover",'.scroller', function(){
var thisId = $(this).attr("id");
if(thisId == "scroll-up1"){
// do your up-scroll
} else if(thisId == "scroll-down1") {
// do your down-scroll
}
});
Mind you, that uses .on(), which is preferred over .bind(), but the idea is to handle it based on a common class, rather than having to modify your selector every time you go to bind your event handler for those items.
Recommended solution: use CLASS NAMES for COMMON FEATURES
$('.scroll-up, .scroll-down').bind({
or even:
$('.scroll').bind({
var id = 38;
$('#scroll-up' + id + ', #scroll-down' + id).bind({ ..............