I'm kind of new to jquery but I'm getting a hang of it. But so far it's been fairly simple jquery.
But I am trying to write a piece of code that is a bit more dynamic
Function: I want the code to hide pictures over different times. Like one picture after 2000 milliseconds, then the next after 4000 milliseconds. But I'm still uncertain on a few things...
This is what I tried:
<div class="twelve columns" style="padding-top: 24px; text-align:center;">
<div>
<img id="1" height="10%" width="10%" src="{{ url('/taskAssets/star.png')}}" />
<img id="2" height="10%" width="10%" src="{{ url('/taskAssets/star.png')}}" />
<img id="3" height="10%" width="10%" src="{{ url('/taskAssets/star.png')}}" />
<img id="4" height="10%" width="10%" src="{{ url('/taskAssets/star.png')}}" />
<img id="5" height="10%" width="10%" src="{{ url('/taskAssets/star.png')}}" />
</div>
<iframe width="560" height="315" src="https://www.youtube.com/embed/4mdQgvGrhwU" frameborder="0" allowfullscreen></iframe>
<hr>
<a href="{{ URL::previous()}}">
<button>Go Back</button>
</a>
</div>
</div>
<!-- Row End-->
</div>
</div>
<script>
var starNumber = 5;
var star = function() {
$("#".starNumber).hide("slow");
starNumber = starNumber - 1;
};
setTimeout(star, 2000);
setTimeout(star, 4000);
setTimeout(star, 6000);
setTimeout(star, 8000);
setTimeout(star, 10000);
</script>
I think the source of the issue is here:
var starNumber = 5;
var star = function() {
$("#" .starNumber).hide("slow");
am I able to call $("#" .starNumber)? I tried also $("#" starNumber) but did not work. How would I perform this?
In your selector $("#" .starNumber) you are not passing a valid string (which jQuery may parse in order to create the appropriate jQuery object). If you are trying to select the element with and id of "5" you must pass the string "#5" to $.
Knowing that the desired form is $("#5"), the easiest option in this case is to change the line in question from:
// This is syntactically incorrect as you are passing an "#" and
// the "starNumber" property of... nothing
$("#" .starNumber).hide("slow");
to:
// This is syntactically CORRECT, as you are concatenating an "#"
// with the value contained in the "starNumber" variable
$("#" + starNumber).hide("slow");
First, your selector need to be $('#' + starNumber) because, JS string concatenation done with +.
And if you need a re-usable function, you might use like following:
var starNumber = 0, timer, offset = 2000;
var star = function () {
if ( starNumber == 5 ) {
clearTimeout(timer);
starNumber = 0;
return;
}
setTimeout(function () {
$("#" + starNumber).hide("slow");
star();
}, offset * ++starNumber);
};
star();
Related
I was looking for a way to change image A to B and B to A by just
clicking them.
So far, this is what I'm using.
<img id="pixelbutton" src="images/pixelbutton.png" />
<img id="pixelbutton2" src="images/pixelbutton_press.png" style="display: none;" />
<script type="text/javascript">
$(document).ready(function(){
$("#pixelbutton").click(function(){
$("#pixelbutton").css({'display':'none'})
$("#pixelbutton2").css({'display':'block'});
})
$("#pixelbutton2").click(function(){
$("#pixelbutton2").css({'display':'none'})
$("#pixelbutton").css({'display':'block'});
})
})
</script>
The script works well for a pair of image.
Now if I have 100 pair of image.
"A <--> B"
"C <--> D"
"E <--> F"
and so on...
Do I have to copy the body HTML and script 100 times and change their ID+URL or there is another more efficient way?
To create hundreds of them... First, use a class.
Then, use a data attribute to store the "alternate" URL.
<img class="pixelbutton" src="images/pixelbutton.png" data-altsrc="images/pixelbutton_press.png"/>
<script type="text/javascript">
$(document).ready(function(){
$(".pixelbutton").click(function(){
// Get the two values
var src = $(this).attr("src");
var altSrc = $(this).data("altsrc");
// Switch them
$(this).attr("src",altSrc).data("altsrc",src);
});
})
</script>
This will work for thousands of .pixelbutton...
;)
EDIT
As per this other .data() documentation, (I wonder why there's two different documentation pages...) the data-* have to be lowercase... Because when trying to get altSrc, it is interpreted as alt-src.
I just learned that... That is quite a strange new standard, from jQuery 3.
So here is your CodePen updated.
You could probably set a naming pattern and use delegation to make an event handler on the images' container.
You could check if the event's target is an image and retrieve its id. Using that id, you could use the pattern you've set to change the images interchangeably.
There are multiple solutions to this, but this is by far the simplest approach:
Wrap your image pairs in a parent <div>
Use .toggleClass() to toggle a class, say .hide, in the images in the element
This solution assumes that you have images in pairs :) see proof-of-concept example:
$(document).ready(function() {
$('img').click(function() {
console.log($(this).siblings());
$(this).add($(this).siblings()).toggleClass('hide');
});
});
/* For layout only */
div {
display: inline-block;
}
/* Used to hide image */
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
Try this one:
jQuery(document).ready(function($) {
var $imgBlock = $('#images');
var html = '';
var imgArr = [
'http://i0.wallpaperscraft.com/image/surface_shape_metal_116716_200x300.jpg',
'http://i0.wallpaperscraft.com/image/universe_space_face_rocket_116714_200x300.jpg',
'http://i0.wallpaperscraft.com/image/letter_surface_wooden_116674_200x300.jpg',
'http://i0.wallpaperscraft.com/image/mountains_lake_reflection_116663_200x300.jpg',
'http://i1.wallpaperscraft.com/image/leaf_drops_surface_116678_200x300.jpg',
'http://i1.wallpaperscraft.com/image/candle_spruce_christmas_decoration_116684_200x300.jpg'
];
$.each(imgArr, function(index, url) {
html += (index % 2 === 0) ? '<div>' : '';
html += '<img src="' + url + '"/>';
html += (index % 2 === 1 || index === imgArr.length - 1) ? '</div>' : '';
});
$imgBlock.append(html);
$imgBlock.on('click', 'img', function(e) {
$(this).parent('div').find('img').removeClass('red');
$(this).addClass('red');
});
});
img {
border: 2px solid #ccc;
}
.red {
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="images"></div>
I would like to use JQuery to load 2 images after the page has loaded. I would like to request and load one image at a time. I tried this, but the requests and loads are happening simultaneously. First image should be come from 'src' and second from'data-src' html attributes.
<img id="image4" src="image/large.jpg" width="100%" data-src="image/full-size.jpg" />
Can anybody help me on this?
Maybe this work for you
$(document).ready(function(){
$('img[data-src]').each(function( key, value ){
var _this = $(this);
var bigImage = _this.attr('data-src');
_this.after('<img class="preLoadingImage'+key+' hide" src="' + bigImage + '" />');
$('.preLoadingImage'+key).one('load',function(){
_this.addClass('hide');
$(this).removeClass('hide');
});
});
});
.hide{ display:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="image4" src="https://upload.wikimedia.org/wikipedia/commons/b/b1/Loading_icon.gif"
width="100%" data-src="http://www.planwallpaper.com/static/images/ZhGEqAP.jpg" />
Without seeing your JS, I believe this is what you want:
var img = $("#image4");
var image1Url = img.attr("src");
var image2Url = img.attr("data-src");
$.get(image1Url)
.done(function () {
$.get(image2Url);
});
I'm not sure you want this but take a look
JS:
setTimeout(function(){
$("#image4").after("<img src='" + $("#image4").attr("data-src") + "' width='100%' />");
},2000);
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id="image4" src="image/large.jpg" width="100%" data-src="image/full-size.jpg" />
I have a div called masterdiv, inside this div there are 3 other div div1, div2, and div3,
This is the html for these html:
<div id="masterdiv" class="masterdivclass">
<div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>
</div>
I also have another div:
<div id=”reload”><img src="reload.png" width="200" height="70" onclick=loadDIV();></div>
What I’m trying to do is to reload the masterdiv div whenever the reload div is clicked on. Hiding and then showing the div isn’t enough as I need the content to be reloaded when the refresh div is clicked on. I don’t want to reload the entire page, just the masterdiv which contains the 3 other div. But I’m not certain this is possible.
I’m trying to do it with this Javascript function:
<script type="text/javascript">
function loadDiv(){
$("<div id="masterdiv" class="masterdivclass">
<div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>
</div>").appendTo("body");
}
</script>
This isn’t working, I think maybe I'm going about this in the wrong way? Maybe I’m missing something very simple here? I’d really appreciate any help with this, thank you in advance!
UPDATE
After reconsidering my project's requirements, I need to change part of my question, I now need to randomise the images displayed in the divs, and have a new random image load every time the reload div is clicked on. I also need to remove each class that’s currently in each of the three divs and then reattach the same classes to the divs (if I don’t remove and reattach the classes then the divs just display the plain images without any class/effect applied to them, it seems like I need to reload the class every time I load an image into a div in order for the class/effect to be applied successfully).
I have 5 images, and I’m using each div’s id tag to attach a random image to each div.
First I’m assigning the 5 different images to 5 different ids:
<script>
document.getElementById('sample1').src="images/00001.jpg";
document.getElementById('sample2').src="images/00002.jpg";
document.getElementById('sample3').src="images/00003.jpg";
document.getElementById('sample4').src="images/00004.jpg";
document.getElementById('sample5').src="images/00005.jpg";
</script>
And then I’m trying to use the following Javascript to load a randomised id (and its assigned image) to each of the 3 divs when the reload div is clicked:
<script>
$(function() {
$('#reload').on('click',function(){
$("#masterdiv").find("div[id^='div']").each(function(index){
//First, remove and reattach classes “div1class”, “div2class” and “div3class”
//from “easyDIV”, “mediumDIV” and “hardDIV” respectively:
$(“#easyDIV”).removeClass('div1class');
$(“#easyDIV”).addClass('div1class');
$(“#mediumDIV”).removeClass('div2class');
$(“#mediumDIV”).addClass('div2class');
$(“#hardDIV”).removeClass('div3class');
$(“#hardDIV”).addClass('div3class');
//Get a random number between 1 and 5, then attach it to “sample”,
//so that the result will be either “sample1”, “sample2”, “sample3”, “sample4” or “sample5”,
//call this variable “variablesample”:
var num = Math.floor(Math.random() * 5 + 1);
variablesample = "sample" +num;
//Attach this randomised id to all three divs using “variablesample”:
jQuery(this).prev("easyDIV").attr("id",variablesample);
jQuery(this).prev("mediumDIV").attr("id",variablesample);
jQuery(this).prev("hardDIV").attr("id",variablesample);
});
var p = $("#masterdiv").parent();
var el = $("#masterdiv").detach();
p.append(el);
});
});
</script>
I’m trying to make it so that all 3 divs will show the same randomised picture (that’s why they’re all sharing the variable “variablesample”), and each div will reload its own class/effect (div1class, div2class and div3class) but it’s not working. I’m not sure if it’s correct to use jQuery inside a Javascript function, or if my syntax for updating the ids of the divs is incorrect.
Perhaps my logic to solving this problem is all wrong? I’d really appreciate any more help with this problem. Thanks again in advance!
Original question was edited many times, so here is the correct answer for the latest edit. Answer to the question; "How to use random image, but same image on all 3, and 3 class on/off switching":
$(function() {
var imageArray = [
'https://via.placeholder.com/40x40',
'https://via.placeholder.com/80x40',
'https://via.placeholder.com/120x40',
'https://via.placeholder.com/160x40',
'https://via.placeholder.com/200x40'];
reloadImages(imageArray);
$('#reload').on('click',function(){
$( "#masterdiv img[id^='div']" ).each(function(index){
$(this).removeClass("div"+(index+1)+"class");
$(this).fadeOut( "slow", function() {
if(index==0) {
reloadImages(imageArray);
}
$(this).addClass("div"+(index+1)+"class");
$(this).fadeIn();
});
});
});
});
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function reloadImages(array){
shuffleArray(array);
for(var i=0;i<3;i++){
// places the first image into all divs, change 0 to i if you want different images in each div
document.getElementById('div'+(i+1)+'id').src=array[0];
}
}
.div1class {
border:2px dashed #0F0;
}
.div2class {
border:2px dashed yellow;
}
.div3class {
border:2px dashed red;
}
#reload {
background-color:blue;
color:white;
width:100px;
height:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='reload'>Click here</div>
<div id="masterdiv" class="masterdivclass">
<div id="div1">
<img src="https://via.placeholder.com/20x40" class="div1class" id="div1id" />
</div>
<div id="div2">
<img src="https://via.placeholder.com/20x40" class="div2class" id="div2id" />
</div>
<div id="div3">
<img src="https://via.placeholder.com/20x40" class="div3class" id="div3id" />
</div>
</div>
Line breaks and un-escaped quotes are why the functions is not working.
function loadDiv(){
$('#masterdiv').remove();
$("<div id='masterdiv' class='masterdivclass'><div id='div1'><img class='div1class' src='image1.jpg' id='div1id' /></div><div id='div2'><img class='div2class' src='image2.jpg' id='div2id' /></div><div id='div3'><img class='div3class' src='image3.jpg' id='div3id' /></div></div>").appendTo("body");
}
try:
function loadDiv(){
$("#masterdiv").load(location.href + " #masterdiv");
}
Here's the code pen demo:
http://codepen.io/anon/pen/xwgRWm
If content of container is not being changed dynamically then there is no point reloading it. appendTo wiil append DOM in existing DOM structure, you will need html() here which will replace the content inside container. Also note you had typo here onclick=loadDiv();
HTML:
<div id="masterdiv" class="masterdivclass">
<div id="div1"><img class="div1class" src="image1.jpg" id="div1id"/></div>
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id"/></div>
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id"/></div>
</div>
<div id="reload"><img src="reload.png" width="200" height="70" onclick=loadDiv();></div>
JS:
function loadDiv() {
$("#masterdiv").html('<div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>\
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>\
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>');
}
This question already has answers here:
Change the image source on rollover using jQuery
(14 answers)
Closed 9 years ago.
Okay, so I have dynamically generated images via PHP, so not necessarily the same images result. And I've spent the last four hours scanning the internet and trying countless things with jQuery and/or CSS, and I've come up with the following that works.
<img style='background:url(images/tile_4.jpg)' src='images/tile_4.jpg' onmouseover="this.src='images/Market.png'" onmouseout="this.src='images/tile_4.jpg'" />
<img style='background:url(images/tile_4.jpg)' src='images/tile_4.jpg' onmouseover="this.src='images/Market.png'" onmouseout="this.src='images/tile_4.jpg'" />
<img style='background:url(images/tile_4.jpg)' src='images/tile_4.jpg' onmouseover="this.src='images/Market.png'" onmouseout="this.src='images/tile_4.jpg'" />
<img style='background:url(images/tile_4.jpg)' src='images/tile_4.jpg' onmouseover="this.src='images/Market.png'" onmouseout="this.src='images/tile_4.jpg'" />
<img style='background:url(images/tile_4.jpg)' src='images/tile_4.jpg' onmouseover="this.src='images/Market.png'" onmouseout="this.src='images/tile_4.jpg'" />
Market.png has a transparent background.
Now, the above works. On mouseover, it displays Market.png with the transparent background part being tile_4.jpg and out mouseout it is tile_4.jpg.
What I want to know: is there ANY way to accomplish the exact same thing as the above with jQuery or CSS? I haven't figured it out, and I've spent hours trying, but I'd rather do something else if at all possible since the above (with massive repetition, the above format is repeated currently around 100 times, but I have plans to expand it to over a 1000 times) will become a bandwidth hog.
You could add a class to each of your <img /> elements, such as 'xyz' (please pick a better name), and then take advantage of the hover() function. Given that your images are dynamic, you could render the image markup with an extra data attribute to serve as the "alternate" or "hover" image source. In the end, you might render something like this:
<img class="xyz" data-alt-src="/images/Market.png" src="/images/tile_4.png" />
<img class="xyz" data-alt-src="/images/Something.png" src="/images/tile_5.png" />
And then to apply the switching functionality for each image, you can write a little function that swaps the image src attribute and the data-alt-src attribute on hover-in/hover-out:
var sourceSwap = function () {
var $this = $(this);
var newSource = $this.data('alt-src');
$this.data('alt-src', $this.attr('src'));
$this.attr('src', newSource);
}
And then it's as simple as executing the function directly using a tiny bit of jQuery event binding:
$(function () {
$('img.xyz').hover(sourceSwap, sourceSwap);
});
Here's a working example (version 1):
var sourceSwap = function () {
var $this = $(this);
var newSource = $this.data('alt-src');
$this.data('alt-src', $this.attr('src'));
$this.attr('src', newSource);
}
$(function () {
$('img.xyz').hover(sourceSwap, sourceSwap);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img class="xyz" data-alt-src="http://cdn1.iconfinder.com/data/icons/fatcow/32/accept.png" src="http://cdn1.iconfinder.com/data/icons/fatcow/32/cancel.png" />
<br/>
<img class="xyz" data-alt-src="http://cdn1.iconfinder.com/data/icons/fatcow/32/accept.png" src="http://cdn1.iconfinder.com/data/icons/fatcow/32/cancel.png" />
<br/>
<img class="xyz" data-alt-src="http://cdn1.iconfinder.com/data/icons/fatcow/32/accept.png" src="http://cdn1.iconfinder.com/data/icons/fatcow/32/cancel.png" />
Here is a spin on Andres Separ's example from the comments. With this selector, you don't need to decorate your images with a marker class. It will also pre-load the alternate source image to help eliminate any lag or flicker when hovering:
$(function() {
$('img[data-alt-src]').each(function() {
new Image().src = $(this).data('alt-src');
}).hover(sourceSwap, sourceSwap);
});
And here's the second version:
var sourceSwap = function () {
var $this = $(this);
var newSource = $this.data('alt-src');
$this.data('alt-src', $this.attr('src'));
$this.attr('src', newSource);
}
$(function() {
$('img[data-alt-src]').each(function() {
new Image().src = $(this).data('alt-src');
}).hover(sourceSwap, sourceSwap);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img data-alt-src="http://cdn1.iconfinder.com/data/icons/fatcow/32/accept.png" src="http://cdn1.iconfinder.com/data/icons/fatcow/32/cancel.png" />
<br/>
<img data-alt-src="http://cdn1.iconfinder.com/data/icons/fatcow/32/accept.png" src="http://cdn1.iconfinder.com/data/icons/fatcow/32/cancel.png" />
<br/>
<img data-alt-src="http://cdn1.iconfinder.com/data/icons/fatcow/32/accept.png" src="http://cdn1.iconfinder.com/data/icons/fatcow/32/cancel.png" />
jQuery
You could use the mouseover and mouseout events :
$("img").on({
"mouseover" : function() {
this.src = 'images/Market.png';
},
"mouseout" : function() {
this.src='images/tile_4.jpg';
}
});
This way you could take out the attributes onmouseout and onmouseover from you HTML and make your code neat.
CSS
However, the easiest way is using CSS:
img {
background-image: url('images/tile_4.jpg');
}
img:hover {
background-image: url('images/Market.png');
}
Sure, with jQuery it is easy.
$('img').hover(function(){
$(this).attr('src','images/Market.png');
},function(){
$(this).attr('src','images/tile_4.jpg');
});
From the following string I need the dynamically changing "6.903" number to make calculation with.
Is there some regular expression or some jQuery trick to do that easily or elegantly?
<a href="javascript:void(0)" class="" id="buddyTrigger">
38.760 <img border="0" align="absmiddle" alt="Arany" src="/img/symbols/res2.gif">
5 <img border="0" align="absmiddle" alt="Pokolkristály" src="/img/symbols/res3.gif">
220 <img border="0" align="absmiddle" alt="Szilánk" src="/img/symbols/res_splinters.png">
91 / 125 <img border="0" align="absmiddle" alt="Akciópont" src="/img/symbols/ap.gif">
6.903 / 82.100 <img border="0" align="absmiddle" alt="Életerő" src="/img/symbols/herz.png">
<img border="0" align="absmiddle" alt="Szint" src="/img/symbols/level.gif"> 41
<img border="0" align="absmiddle" alt="Harci érték" src="/img/symbols/fightvalue.gif"> 878</a>
Here is my code as lenghty solution, can I simplify somehow?
<script type="text/javascript">
var dataIn=$('#infobar div.gold').html();
var dataPrep2Split=dataIn.replace(/<img(.*)>/g,';');
var dataSplit=dataPrep2Split.split(';');
var myData2Int=parseInt(dataSplit[18].replace('.',''));
if(myData2Int<=10000) {
$('#player').find('button.btn').remove();
var putBack=dataIn.replace(dataSplit[18],'<span class="newmessage">'+dataSplit[18]+'</span>');
$('#infobar div.gold').html(putBack);
}
</script>
Use DOM methods; replacing things using .html() often breaks page features. Also, that regex is liable to break with the smallest change.
You're trying to grab the Life value right? And that ends with the <img> with alt="Életero".
So that text node is (based on the Q code):
var lifeValTxtNd = $("#buddyTrigger img[alt='Életero']")[0].previousSibling;
And this gets 6903 from the contents like 6.903 / 82.100:
var lifeVal = $.trim (lifeValTxtNd.nodeValue)
.replace (/^\s*(\d*)\.?(\d+)\s*\/.+$/, "$1$2")
;
lifeVal = parseInt (lifeVal, 10);
Then to wrap that section in a span use:
$("#buddyTrigger img[alt='Életero']").before (
'<span class="newmessage">' + lifeValTxtNd.nodeValue + '</span>'
);
lifeValTxtNd.parentNode.removeChild (lifeValTxtNd);
Doing it this way:
Won't break any event listeners on the page.
Is less susceptible to changes in the page layout/content.
Is easier to understand and maintain.
Will run faster, if performance is a factor.