I can't get the following function to work.
On click of class .image, content in 3 divs (gallerytext, image, and thumbset) is to be replaced. I have been trying to get this to work for days now and I cannot figure out what I am doing wrong.
My code:
// Init load
$(document).ready(function() {
var $doc = $(document.body);
var text = $('#gallerytext1').html(); //blank divs are filled with content on page load
$('#gallerytext').html(text);
var thumbset = $('#thumbset1').html();
$('#thumbset').html(thumbset);
$('#image').html('<img src="images/edwards1.jpg" border="0"/>');
//click handler
$doc.on("click",".image",function(){
var image=$(".image").attr("rel");
var imid=$(".image").attr("data");
var text=$('#gallerytext'+imid).html();
var thumbset=('#thumbset'+imid).html();
$('#debug').html(imid);
$('#gallerytext').fadeIn('slow');
$('#gallerytext').html(text);
$('#thumbset').fadeIn('slow');
$('#thumbset').html(thumbset);
$('#image').hide();
$('#image').fadeIn('slow');
$('#image').html('<img src="' + image + '"/>');
return false;
});
});
The initial content loads just fine but I cannot get the click handler to work. Objects with the class .image are formatted as such:
<img src="images/edwardsthumb2.jpg" class="thumb" border="0"/>
Any assistance would be highly appreciated, thank you.
These are probably your problematic lines:
var image=$(".image").attr("rel");
var imid=$(".image").attr("data");
$(".image") selects all of the elements with a class of image. You want just the one that was clicked, so use this to refer to it:
var image = $(this).attr("rel");
var imid = $(this).attr("data");
Also, don't make up custom attributes like data. HTML5 introduced data- attributes which are used to store custom data types, so use them:
data-number="1"
And you can access it with the .data() method:
var imid = $(this).data('number');
Related
I am using Materialize CSS and have the "Material Box" which is a lightbox plugin. I want all of the thumbnails to be the same size. When clicked I want the full photo to load.
I am using onclick to change the src. How do I change it back to the thumbnail when the large photo closes (either with a click or the escape key)?
<div class="col s6 m3">
<img class="materialboxed responsive-img" src="images/thumb1.jpg" onclick='this.src="images/photo1"'>
</div>
Material Box Javascript
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.materialboxed');
var options = {}
var instances = M.Materialbox.init(elems, options);
});
// Or with jQuery
$(document).ready(function(){
$('.materialboxed').materialbox();
});
Materializecss.com - https://materializecss.com/media.html
I haven't found an easy other way of achieving the lightbox effect with cropped square thumbnails. Any advice would be greatly appreciated!
Here is one implementation of what you want, keeping track of the image click state.
$(document).ready(function(){
$('.materialboxed').materialbox();
// Image sources
const srcThumb = '/images/thumb1.jpg'
const srcPhoto = '/images/photo1.jpg'
// Click state
var clicked = false
// Get image element and bind click event
const img = $('.materialboxed')
img.on('click', function() {
img.attr('src', clicked ? srcPhoto : srcThumb)
clicked = !clicked
})
});
No need to rely on onclick in this case.
Materialize is already binding onclick for those images.
And it provides the following native methods we can use for doing exactly what you want using pure JS (no jQuery):
onOpenStart Function null Callback function called before materialbox is opened.
onCloseEnd Function null Callback function called after materialbox is closed.
In this example below, we assume there is a normal materialboxed photo gallery containing thumbnails named thumb_whatever.jpg, for example. But we're also serving the original sized photo named whatever.jpg in the same directory.
Then we're changing src attribute dynamically removing the thumb_ prefix to get the original image, which in this case will be imediately lightboxed by materialize.
And after closing the lightbox, the src attribute is being set back again without the thumb_ prefix.
We do that while initializing Materialbox:
// Initializing Materialbox
const mb = document.querySelectorAll('.materialboxed')
M.Materialbox.init(mb, {
onOpenStart: (el) => {
var src = el.getAttribute('src') // get the src
var path = src.substring(0,src.lastIndexOf('/')) // get the path from the src
var fileName = src.substring(src.lastIndexOf('/')).replace('thumb_','') // get the filename and removes 'thumb_' prefix
var newSrc = path+fileName // re-assemble without the 'thumb_' prefix
el.setAttribute('src', newSrc)
},
onCloseEnd: (el) => {
var src = el.getAttribute('src') // get the src
var path = src.substring(0,src.lastIndexOf('/')) // get the path from the src
var fileName = src.substring(src.lastIndexOf('/')).replace('/', '/thumb_') // get the filename and adds 'thumb_' prefix
var newSrc = path+fileName // re-assemble with the 'thumb_' prefix
el.setAttribute('src', newSrc)
}
})
This solution is also working like a charm for me, crossplatform.
$(document).ready(function(){
function createPopup(event){
$('<div class="popup"><img src="mysrc.jpg" img style="opacity=0.5; width:50px; height:50px;"></img></div>').appendTo('body');
positionPopup(event);
};
function positionPopup(event){
var tPosX = 950;
var tPosY = event.clientY+25;
$('div.popup').css({'position': 'absolute', 'top': tPosY, 'left':tPosX});
$('#test').attr('ydown', parseInt(tPosY)+ parseInt(add));
};
var elements = document.getElementsByTagName('cposs');
for(var i = 0; i < elements.length; i++){
var imagetest = document.createElement("img");
imagetest.src = "mysrc.jpg";
elements[i].onmouseover = function(){
this.style.background = 'Green';
createPopup(event);
}
elements[i].onmouseout = function(){
this.style.background = '';
}
var ycoor= $('#test').attr('ydown');
$( "#test" ).append( "<a href=http://www.google.com><img src='mysrc.jpg'</img></a>" );
}
});
</script>
<div id="test" ydown="<?php echo $ydown; ?>" xdown="<?php echo $xdown; ?>">
There is then multiple paragraphs with <cposs></cposs> tags and this allows the text to be highlighted when the mouse is hovered over and creates a popup image to the right of the paragraph. I also have for each counted <cposs></cposs> an image that is displayed in the test div.
There is a couple things I was hoping I would be able to accomplish:
On page load, I would like an image to be displayed at the end of each <cposs></cposs> text. Instead of fixed coordinates.
I would like these images to execute a function when clicked on.(Tried adding the "onclick" attribute but said the function was not defined)
Eventually, I would like the clickable images to cause the text between the cposs tags to highlight. Similar to what I have now, but instead of mouse over, its a click event.
EDIT:
I have tried to add an onclick attribute to the appended image but once the image is clicked, says the function is not defined.
I am unsure on how to get the coordinates of the cposs tags. I am confused on if I am able to use offset and or position function in javascript. I have attempted to use both and have not succeeded.
I guess all I really need to know if how to get the end coordinates of the cposs tags and how to give each displayed image a clickable function
I am a big fan of jsfiddle!
Any sort of help is greatly appreciated!
Thanks in advance.
Here's a jsFiddle example: https://jsfiddle.net/sn625r3z/14/
To make freshly added elements clickable you should be using jQuery's ".on" function and pass an event to it. Something like this:
$('img.new-image').on('click', function(){
$(this).parent().css({background: 'green'});
});
In the jsFiddle example I positioned images with CSS. But if you want to get the coordinates to position the image at the end of the block I would do it like this:
$('cposs').each(function(){
var el = $(this);
var width = el.width();
var height = el.height();
var newElement = $('<img class="new-image" src="'+imagetest.src+'" />');
el.append(newElement);
newElement.css({top: height+"px", left: width+"px"});
});
Hope this helps.
I've got the following script which swaps the source of an image. However currently this happens after the page loads so the user experiences a split second of seeing one picture before it switches to the correct image.
<script>
window.onload = function () {
var winnerName = $("#leaderboard tr td:eq(1)").text().trim();
$("#pictureDiv img").attr("src", "/Content/Images/" + winnerName + ".jpg");
};
</script>
How can I get the image to switch before loading?
Note I've also tried:
<script>
$(function() {
var winnerName = $("#leaderboard tr td:eq(1)").text().trim();
$("#pictureDiv img").attr("src", "/Content/Images/" + winnerName + ".jpg");
});
</script>
but this results in the same thing occurring
Both of the window.onload or jQuery's $(function()... functions are only called when the page is fully loaded.
The closest you could get is to add the function to the images onload handler.
<img src="..." onload="function() {...}">
But I suspect the same will still occur.
If the image's src needs to be set using javascript then you could try dynamically creating the image and adding it in where you need it, using something like the following.
$(function() {
var winnerName = $("#leaderboard tr td:eq(1)").text().trim();
var imgElement = $('<img>').attr("src", "/Content/Images/" + winnerName + ".jpg");
$("#pictureDiv").append(imgElement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pictureDiv"></div>
I have a slider working with images and variables set that grab data from that slide. That data is manipulated by me to create certain functionality.
I currently have a set of images that move across(slider) on my body of the page I have a social bar that is always foxed to the right of the page.
What I am trying to do is grab the data and change the urls, and text inside the social buttons each time the slide is changed using the callback function provided by the slider. Here is my code:
var $mainContainer = $('div#container');
var $tmbContainer = $('.rsThumbsContainer');
var $tmbContainerT = $('.rsThumbsContainer').find('.rsThumb');
var $slider = $('#gallery-t-group');
var $body = $('body');
var $close = $('<div id="close"><p class="icon-close"></p></div>');
$tmbContainerT.each(function () {
//console.log(slider.currSlide);
$(this).on('click', function(event) {
$('body').addClass('rsSlider-active');
sliderR();
var $gallery = $('#gallery-t-group').find('.portfolio');
$gallery.each(function () {
var src = this.href;
var content = $(this).find('.perma_link').val();
var textContent = $(this).find('img').attr('alt'); // same as $(this.element).attr("title"); before you modify it using this.title +=
var image = $(this).find('img').attr('src'); // this is the URL of the thumbnail
var imageAlt = $(this).find('img').attr('alt');
var $tumbl = $(this).find('a.tumbl-button');
$tumbl.attr("href","http://www.tumblr.com/share/photo?source="+ encodeURIComponent(image) +"&caption="+ encodeURIComponent(textContent) +"&clickthru="+ encodeURIComponent(content) +"");
slider.ev.on('rsAfterSlideChange', function(event) {
$('#twit').html('<div id="twitter" data-url="'+content+'" data-text="'+textContent+'"></div>');
$('#twitter').attr("data-url",content);
$('#twitter').attr("data-text",textContent);
$('#twitter').sharrre({
share: {
twitter: true
},
template: '<a class="box" href="#"><div class="count" href="#">{total}</div><div class="share"><span></span>Tweet</div></a>',
enableHover: false,
enableTracking: true,
buttons: { twitter: {via: '_JulienH'}},
click: function(api, options){
api.simulateClick();
api.openPopup('twitter');
}
});
});
});
slider.updateSliderSize(true);
});
});
This is where all my social buttons get added:
<div class="socialbar-vertical">
<div id="socio-box">
<div id="twit"></div>
<div id="facebook" data-url="http://sharrre.com/" data-text="Make your sharing widget with Sharrre (jQuery Plugin)"></div>
<div id="googleplus" data-url="http://sharrre.com/" data-text="Make your sharing widget with Sharrre (jQuery Plugin)"></div>
</div>
</div>
Currently this is all I have that changes the content of a div but it always uses the first clicked div:
$('#twit').html('<div id="twitter" data-url="'+content+'" data-text="'+textContent+'"></div>');
what I want to do is keep changing the attr's of that div everytime the slide changes.
Am I doing something completely wrong here or missing a trick?
a.) Why dont you just store the #twit.attr before you replace the div and then assign the value after replacement.
//Make a copy of all attributes of #twit
//TODO Replace #twit
//TODO set all attributes to the new #twit
b.) Another option is to stop replacing #twitter completely and instead re-using it (including its children). Might be less resource consuming.
I have an img html block <img src="folder1/folder2/folder3/logo1.png"> positioned inside a big div like this
<div id="editorial">
<div id="img_editorial"><img src="folder1/folder2/folder3/logo1.png" /></div>
</div>
When user hovers the <div id="editorial"> (mouseover) i want to read the attribute of <img> which is folder1/folder2/folder3/logo1.png extract the logo1.png from this and add on_ to the logo ( on_logo1.png ) and then output it with jquery .html() function to overwritte <div id="img_editorial">
On mouseout i want to return to logo1.png ... because i have multiple background changes in that parent div ... so the basic functionality is to grayout a logo when mouse is over a big div (also div`s background changes ... etc) ...
So .. how can i read the <img> attribute and then extract logo1.png and not the whole folder1/folder2/folder3/logo1.png ...
You can read the attribute like this:
var img_src = $('#img_editorial img').attr('src');
This will give you:
folder1/folder2/folder3/logo1.png
Than you can split it with:
var split_img_src = img_src.split('/');
This will give you an array, something like:
split_img_src[0] = folder1;
split_img_src[1] = folder2;
split_img_src[2] = folder3;
split_img_src[3] = logo1.png;
so the last value in the array should always be the name of the file - no matter how long the directory tree is.
So you now have the file name, you can append what ever you want to it and do what ever you need.
Good luck.
Here! just a nice solution:
$('#img_editorial img').hover(function(){
imgSrc = $(this).attr('src');
var imgSplit = imgSrc.split('/');
var imgName = imgSplit[3];
$(this).attr('src', imgSrc.replace(imgName, 'on_'+imgName) );
},function(){
$(this).attr('src', imgSrc);
});
If you want, open Firebug and play with this DEMO
The following should do what you want. It just stores the original image using the jQuery .data() API and puts it back when on .mouseleave() of the <div>.
$('div#editorial').mouseenter(function() {
var originalSrc = $('img', this).prop('src');
$(this).data('originalSrc', originalSrc);
var pathComponents = originalSrc.split('/');
var logo = pathComponents.pop();
pathComponents.push('on_' + logo);
$('img', this).prop('src', pathComponents.join('/'));
}).mouseleave(function() {
$('img', this).prop('src', $(this).data('originalSrc'));
});
The demo sort of works but I have no _on image so it just 404s. I hope you get the idea :-)