For a prototype website, I have downloadded the free bootstrap template that can be found on this website : http://themes.3rdwavemedia.com/demo/prettydocs/index.html
As you can see on the index page of the template, the six item boxes all have the same size, despite the lenght of their content. If we inspect the DOM with Firebug, we can see that every item box is defined as a div :
<div class="item item-green col-md-4 col-sm-6 col-xs-6">
<div class=item-inner" style="height: 237px;">
...
</div>
</div>
Now, when I edit the index.html page downloadded with the template package, I see that those item div have no predefined height. The property seems to be added once the page is loadded.
What I want to do is to make the box list dynamic according to a parameter. Depending on the value of this parameter, there might be 2, 3, 7, 15 boxes, each with a specific icon, color, title, content and link.
In the index.html file, I have added the following onLoad method linked to a personnal Javascript file :
<body class="landing-page" onload="addItemBoxes()">
Then, in my Javascript file, i have a few fonctions to define the list of boxes to add, and then I use a loop calling a function like this :
function addBox(boxId) {
var boxDetails = getBoxDetails(boxId);
/*
Example of boxDetails content :
{
boxId : "1",
boxTitle : "Cars",
boxDescription : "This is a page that talks about cars",
boxIcon : "fa-automobile",
boxIconSource : "font-awesome",
boxLink : "cars.html"
}
*/
if (boxDetails) {
//Main div
var cardsWrapperDiv = document.getElementById("cards-wrapper");
//Get color from the global var
var nbrOfItems = cardsWrapperDiv.getElementsByClassName("item").length;
var nbrOfColors = COLORS.length;
var colorIndex = nbrOfItems % nbrOfColors;
var color = COLORS[colorIndex];
//Create the box
var itemDiv = document.createElement("div");
itemDiv.className = "item " + color + " col-md-4 col-sm-6 col-xs-6";
//Content of the box
var innerItemDiv = document.createElement("div");
innerItemDiv.className = "item-inner";
//Icon
var iconHolderDiv = document.createElement("div");
iconHolderDiv.className = "icon-holder";
if (boxDetails.boxIconSource == 'font-awesome') {
var i = document.createElement("i");
i.className = "icon fa " + boxDetails.boxIcon;
iconHolderDiv.appendChild(i);
} else if (boxDetails.boxIconSource == 'elegant_font') {
var iconSpan = document.createElement("span");
iconSpan.setAttribute("aria-hidden", "true");
iconSpan.className = "icon " + boxDetails.boxIcon;
iconHolderDiv.appendChild(iconSpan);
} else {
console.log("No icon!");
}
innerItemDiv.appendChild(iconHolderDiv);
//Title
var h3 = document.createElement("h3");
h3.className = "title";
h3.innerText = boxDetails.boxTitle;
innerItemDiv.appendChild(h3);
//Description
var p = document.createElement("p");
p.className = "intro";
p.innerText = boxDetails.boxDescription;
innerItemDiv.appendChild(p);
//Link
var a = document.createElement("a");
a.className = "link";
a.href = boxDetails.boxLink;
var span = document.createElement("span");
a.appendChild(span);
innerItemDiv.appendChild(a);
itemDiv.appendChild(innerItemDiv);
cardsWrapperDiv.appendChild(itemDiv);
}
}
The code works fine, except that the boxes have no style height assigned. When I inspect them with Firebug, I see their definition such as :
<div class="item item-green col-md-4 col-sm-6 col-xs-6">
<div class=item-inner">
...
</div>
</div>
Therefore, their height depends on the lenght of the content, and this is not pretty at all...
I suspect that the height is assigned with one of the scripts referenced at the bottom of the index.html code :
<script type="text/javascript" src="assets/plugins/jquery-1.12.3.min.js"></script>
<script type="text/javascript" src="assets/plugins/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="assets/plugins/jquery-match-height/jquery.matchHeight-min.js"></script>
<script type="text/javascript" src="assets/js/main.js"></script>
But I have no idea how to call them so that the height problem is fixed. Thank you very much for your help!
If you want to add style into the div using javascript, you can use:
//Content of the box
var innerItemDiv = document.createElement("div");
innerItemDiv.className = "item-inner";
innerItemDiv.style.height="237px"; // This is the line to add
Did not test the code, but I think it should work.
You can try doing overflow auto, or use the bootstrap elements class names/ids to adjust size. There is also the option to do nedia queries
I found in the main.js script associated with the template those few lines :
/* ======= jQuery Responsive equal heights plugin ======= */
/* Ref: https://github.com/liabru/jquery-match-height */
$('#cards-wrapper .item-inner').matchHeight();
$('#showcase .card').matchHeight();
If I add the two jquery calls at the end of my personal addBox function, it works. All the new boxes have a similar size, properly adjusted if the screen size changes.
Thank you all for your help.
Related
I need to make the background image in div tag and it has to change automatically, I already put the array of images inside the javascript, but the images is not showing when i'm run the site.The background should behind the menu header.
This is the div
<div style="min-height:1000px;position:relative;" id="home">
below of the div is containing the logo, menu and nav part.
<div class="container">
<div class="fixed-header">
<!--logo-->
<div class="logo" >
<a href="index.html">
<img src="images/logo.png" alt="logo mazmida" height="142" width="242">
</a>
</div>
<!--//logo-->
This is the javascript
<script>
var imgArray = [
'images/1.jpg',
'images/2.jpg',
'images/3.jpg'],
curIndex = 0;
imgDuration = 2000;
function slideShow() {
document.getElementID('home').src = imgArray[curIndex];
curIndex++;
if (curIndex == imgArray.length) { curIndex = 0; }
setTimeout("slideShow()", imgDuration);
}
slideShow();
You have a few issues with your script. I've made a live JSbin example here:
https://jsbin.com/welifusomi/edit?html,output
<script>
var imgArray = [
'https://upload.wikimedia.org/wikipedia/en/thumb/0/02/Homer_Simpson_2006.png/220px-Homer_Simpson_2006.png',
'https://upload.wikimedia.org/wikipedia/en/thumb/0/0b/Marge_Simpson.png/220px-Marge_Simpson.png',
'https://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png'
];
var curIndex = 0;
var imgDuration = 1000;
var el = document.getElementById('home');
function slideShow() {
el.style.backgroundImage = 'url(' + imgArray[curIndex % 3] + ')';
curIndex++;
setTimeout("slideShow()", imgDuration);
}
slideShow();
</script>
There are a few issues with your script:
On the element since it's a div not an img, you need to set style.backgroundImage instead of src. Look at https://developer.mozilla.org/en-US/docs/Web/CSS/background for other attributes to related to background image CSS
Also it's document.getElementById
Optimizations
And you can use mod % trick to avoid zero reset
Use setInterval instead of setTimeout
Further optimzations
Use requestAnimationFrame instead of setTimeout/setInterval
I suggest getting familiar with your browser debugging tools which would help identify many of the issues you face.
document.getElementID('home').src = imgArray[curIndex]
You are targeting a div with an ID of home, but this is not an Image element (ie ,
But since you want to alter the background colour of the DIV, then you use querySelector using javascript and store it in a variable, then you can target the background property of this div (ie Background colour).
I hope this helps.
You are trying to change the src property of a div, but divs do not have such property.
Try this:
document.getElementById('home').style.backgroundImage = "url('" + imgArray[curIndex] + "')"
This changes the style of the target div, more precisely the image to be used as background.
As you want to change the background image of the div, instead of document.getElementID('home').src = imgArray[curIndex] use
document.getElementById("#home").style.backgroundImage = "url('imageArray[curIndex]')";
in JavaScript or
$('#home').css('background-image', 'url("' + imageArray[curIndex] + '")'); in jquery.
To achieve expected result, use below option of using setInterval
Please correct below syntax errors
document.getElementID to document.getElementById
.src attribute is not available on div tags
Create img element and add src to it
Finally use setInterval instead of setTimeout outside slideShow function
var imgArray = [
'http://www.w3schools.com/w3css/img_avatar3.png',
'https://tse2.mm.bing.net/th?id=OIP.ySEgAgJIlDQsIQTu_MeoLwHaHa&pid=15.1&P=0&w=300&h=300',
'https://tse4.mm.bing.net/th?id=OIP.wBAPnR04OfXaHuFI9Ny2bgHaE8&pid=15.1&P=0&w=243&h=163'],
curIndex = 0;
imgDuration = 2000;
var home = document.getElementById('home')
var image = document.createElement('img')
function slideShow() {
if(curIndex != imgArray.length-1) {
image.src = imgArray[curIndex];
home.appendChild(image)
curIndex++;
}else{
curIndex = 0;
}
}
setInterval(slideShow,2000)
<div style="position:relative;" id="home"></div>
code sample - https://codepen.io/nagasai/pen/JLKvME
I have a gallery page that is updated often with new images. I use simple HTML to post the photos. My process currently is copy and paste the set of tags for a photo and change the number to correspond with the image file name. E.G. I change the number 047 to 048. Copy-Paste, change it to 049. This goes on until I have reached the number of additional photos. As you can see, this is very inefficient and there must be a better way of doing this. I was wondering if there is a simpler way to achieve this with Javascript? Perhaps generate additional tags by inputing a certain number or range?
Any ideas that would make this process efficient are welcomed please! Thank you!
<div class="cbp-item trim">
<a href="../assets/images/trim/img-trim-047.jpg" class="cbp-caption cbp-lightbox" data-title="">
<div class="cbp-caption-defaultWrap">
<img src="../assets/images/trim/img-trim-047.jpg" alt="">
</div>
</a>
</div>
You could use a templating solution. There are several libraries for that, but you can also implement it yourself.
Here is one way to do that:
Put the HTML for one image in a script tag that has a non-standard language property so the browser will just ignore it
Put some keywords in there that you'll want to replace, e.g. {url}. You can invent your own syntax.
Read that template into a variable
In the JS code, put all the images' URLs in an array of strings
For each element in that array, replace the keywords in the template string with that particular URL, and concatenate all these resulting HTML snippets.
Inject the resulting HTML into the appropriate place in the document.
Here is a snippet doing that:
// Add new images here:
var images = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/330px-SNice.svg.png",
"https://nettemarie357.files.wordpress.com/2014/09/smiley-face.jpg?w=74&h=74",
];
// Load the template HTML
var template = document.querySelector('script[language="text/template"]').innerHTML;
// Use template to insert all the images:
container.innerHTML = images.map(url => template.replace(/{url}/g, url)).join('');
img { max-width: 50px }
<div id="container"></div>
<script language="text/template">
<div class="cbp-item trim">
<a href="{url}" class="cbp-caption cbp-lightbox" data-title="">
<div class="cbp-caption-defaultWrap">
<img src="{url}" alt="">
</div>
</a>
</div>
</script>
This would help you creating it programatically:
var new_row = document.createElement('div');
new_row.className = "cbp-item trim";
var a = document.createElement('a');
a.href = "../assets/images/trim/img-trim-047.jpg";
a.className= "cbp-caption cbp-lightbox";
document.body.appendChild(a);
var div = document.createElement('div');
div.className = "cbp-caption-defaultWrap";
var img = document.createElement('img');
img.src= "../assets/images/trim/img-trim-047.jpg";
div.appendChild(img);
a.appendChild(div);
new_row.appendChild(a);
If it is just about printing HTML, I suggest you to use plugins like Emmet for Sublime Text editor.
When you install this plugin and see how it works, you can simple create a complex html in a way that 'for' loop would do this. This will help you to change only the image/link number of every item.
Check the demo in the link, that I added.
Here's an example in Java Script that will generate the html you will need. Set the total to whatever number you need to generate the number of images you want.
var total = 47;
var hook = document.getElementById('hook');
// Main Node for SlideShow
var node = document.createElement('div');
node.classList = "cbp-item trim";
// Work out the correct number
var n = function(int) {
var length = int.toString().length;
return length === 1
? '00' + int
: length === 2
? '0' + int
: length
}
// Create the item
var createItem = function(int){
// Create Anchor
var a = document.createElement('a');
a.href = '../assets/images/trim/img-trim-' + ( n(int) ) + '.jpg" class="cbp-caption cbp-lightbox';
a.classList = 'cbp-caption cbp-lightbox';
// Create Div
var div = document.createElement('div');
div.classList = 'cbp-caption-defaultWrap';
// Create Image
var img = document.createElement('img');
img.src = '../assets/images/trim/img-trim-' + ( n(int) ) + '.jpg';
img.alt = 'gallery image';
// Finalise Dom Node
var container = div.appendChild(img)
a.appendChild(div);
// Return Final Item
return a
}
// Create Items
for (var i = 1; i < total + 1; i++) {
node.appendChild(createItem(i));
}
// Append Main Node to Hook
hook.appendChild(node);
<div id="hook"></div>
Before I get in to this, I know I should learn jQuery but I haven't got to that yet, I want to learn raw JavaScript first! Well, mostly. Can someone help me without the use of jQuery please just for understanding, thank you!:
Hi, I'm new to JavaScript, not long started learning it as you can see by the first code (which works so I'm leaving it) for the navigation.
However, my problem comes on the 2nd piece of code I'm trying something from a different angle after watching videos on event listeners etc and everything I have written makes sense, to me, I'm going through it step by step, it's selecting all the right stuff, but it's still not showing the desired result!!
When you click CSS i want it to show the div with id "cs", and same for the HTML and JavaScript ones.
I really don't know JavaScript enough to solve this myself, I can not think of anything AT ALL to help with the problem!
Somebody save me, please, my mind is going crazy and I want to go to bed!
Here is the code, and here is the JS fiddle: https://jsfiddle.net/pmj26o9p/2/
var htm = document.getElementById('htm');
var css = document.getElementById('css');
var js = document.getElementById('js');
htm.addEventListener("click", contentShow);
css.addEventListener("click", contentShow);
js.addEventListener("click", contentShow);
function contentShow() {
var whichOne = this.attributes["data-id"].value;
var switcheroo = document.getElementById(whichOne);
switcheroo.onclick = function() {
if (switcheroo.style.display === "none") {
switcheroo.style.display = "";
} else {
switcheroo.style.display = "none";
}
}
EDIT: On reading through the code again I don't think it will achieve what I want even if it works. This will let me show and hide whichever I'm clicking right?
I want to show the clicked one but then hide / apply display:none to all others that aren't clicked.
My example below will show the chosen block and hide the others, as per your EDIT comment.
var htm = document.getElementById('htm');
var css = document.getElementById('css');
var js = document.getElementById('js');
function contentShow(el) {
var whichOne = el.attributes["data-id"].value;
var switcheroo = document.getElementById(whichOne);
// show selected block, hide the others
switch (switcheroo) {
case htm:
htm.style.display = "block";
css.style.display = "none";
js.style.display = "none";
break;
case js:
htm.style.display = "none";
css.style.display = "none";
js.style.display = "block";
break;
case css:
htm.style.display = "none";
css.style.display = "block";
js.style.display = "none";
break;
}
}
<span data-id="htm" onClick="contentShow(this)" style="margin-right:10px;color:red; cursor:pointer">Click to show the HTML Block</span>
<span data-id="css" onClick="contentShow(this)" style="margin-right:10px;color:green; cursor:pointer">Click to show the CSS Block</span>
<span data-id="js" onClick="contentShow(this)" style="margin-right:10px;color:blue; cursor:pointer">Click to show the JS Block</span>
<br/>
<br/>
<div id="htm">Some HTML info here</div>
<div id="css" style="display:none">Some CSS info here</div>
<div id="js" style="display:none">Some JavaScript info here</div>
you are binding a second event handler to the switcheroo element, but the click event is not triggered so nothing happens.
If you want to make a toggle function on the switcheroo variable, you should do this instead:
function contentShow() {
var whichOne = this.attributes["data-id"].value;
var switcheroo = document.getElementById(whichOne);
return toggleDisplay(switcheroo);
}
function toggleDisplay(elem) {
if (elem.style.display === "none") {
elem.style.display = "";
} else {
elem.style.display = "none";
}
}
Ignoring your other bad practices, change
var htm = document.getElementById('htm');
var css = document.getElementById('css');
var js = document.getElementById('js');
htm.addEventListener("click", contentShow);
css.addEventListener("click", contentShow);
js.addEventListener("click", contentShow);
function contentShow() {
var whichOne = this.attributes["data-id"].value;
var switcheroo = document.getElementById(whichOne);
switcheroo.onclick = function() {
if (switcheroo.style.display === "none") {
switcheroo.style.display = "";
} else {
switcheroo.style.display = "none";
}
}
to something more like:
var doc = document;
function E(id){
return doc.getElementById(id); // you guessed it - same as document.getElementById, without typing it every time
}
var htm = E('htm'), css = E('css'), js = E('js');
contentShow = (function(){ // self-executing scopes off var showing - variable style assignment requires function definition before execution
var showing = false;
return function(){ // returns unexecuted function
var ht = E('ht').style, cs = E('cs').style, jsc = E('jsc').style;
if(showing){
ht.display = cs.display = jsc.display = 'none'; showing = false;
}
else{
ht.display = cs.display = jsc.display = 'block'; showing = true;
}
}
})();
htm.addEventListener('click', contentShow);
css.addEventListener('click', contentShow);
js.addEventListener('click', contentShow);
See updated JSFiddle here.
If there are no other click Events on those Elements, you could even change
htm.addEventListener('click', contentShow);
css.addEventListener('click', contentShow);
js.addEventListener('click', contentShow);
to
htm.onclick = css.onclick = js.onclick = contentShow;
JSFiddle here
but keep in mind this technique overwrites previous Events of the same type.
Here is a variation of #K Scandrett answer which add some scalability/flexibility
var navElements = document.getElementsByClassName("nav");
//Add Event Listeners
for(var i = 0; i < navElements.length; i ++)
{
navElements[i].addEventListener('click', contentShow, false);
}
function contentShow(el) {
var whichOne = el.target.attributes["data-id"].value;
var target = document.getElementById(whichOne);
for(var i = 0; i < navElements.length; i ++)
{
var content = document.getElementById(navElements[i].attributes["data-id"].value)
content.style.display = content === target ? "block" : "none";
}
}
<span data-id="htm" style="margin-right:10px;color:red; cursor:pointer" class="nav">Click to show the HTML Block</span>
<span data-id="css" style="margin-right:10px;color:green; cursor:pointer" class="nav">Click to show the CSS Block</span>
<span data-id="js" style="margin-right:10px;color:blue; cursor:pointer" class="nav">Click to show the JS Block</span>
<br/>
<br/>
<div id="htm">Some HTML info here</div>
<div id="css" style="display:none">Some CSS info here</div>
<div id="js" style="display:none">Some JavaScript info here</div>
I know you're looking for a javascript solution here.and kudos to you for wanting to understand javascript before getting into jquery, but here is an out of the box solution for you.... pure HTML and CSS
.info {display:none;}
.info:target{display:block;}
Click to show the HTML Block
Click to show the CSS Block
Click to show the JS Block
<br/>
<br/>
<div id="htm" class="info">Some HTML info here</div>
<div id="css" class="info">Some CSS info here</div>
<div id="js" class="info">Some JavaScript info here</div>
What I've done here is, leverage internal page id links and the :target selector. In my mind, this is more semantic and can also still be extended by scripting while still maintaining semantics. This option also gives your uses the option of bookmarking selections etc.
CSS OPTION 2
This option achieves the initial display. It is not as clean and uses absolute positioning and z-indexes. Alos note that is uses a background color to conceal the initial option.
.info {position:relative;}
.info > div {
position:absolute;
top:0;
left:0;
background-color:#FFF;
z-index:10;
display: none;
}
#htm
{
display:block;
z-index:1;
}
.info > div:target {
display: block;
}
Click to show the HTML Block
Click to show the CSS Block
Click to show the JS Block
<br/>
<br/>
<div class="info">
<div id="htm">Some HTML info here</div>
<div id="css">Some CSS info here</div>
<div id="js">Some JavaScript info here</div>
</div>
On a side note you should consider adding/removing css classes using javascript instead of the display property directly. This will enable the use of CSS transitions.
I'm working on this project, and what it is supposed to do is show a series of "business cards" that contain the name of someone and their image. When you hover over the card an x button appears and clicking it will delete the card from the page. There are also to inputs one for the url of an image and another for the name of the person, under these 2 inputs are a submit button, and when it's submitted it's supposed to create the card.
Right now I have the code to create the card, but it does not appear to be working.
document.getElementById('btn').onclick = function() {
var addPhoto = document.getElementById('imagename').value,
src = addPhoto +'.png',
img = document.createElement('img');
img.src = src;
var addName =document.getElementById('actorname').value;
var card = document.createElement('div');
card.setAttribute('class','card');
var title = document.createElement('h1');
container.innerHTML = addName;
var cardImage = document.createElement('div');
cardImage.setAttribute('class','card-image');
var img = document.createElement('img');
image.setAttribute('src',addPhoto);
var button = document.createElement('input');
button.setAttribute('class','buttons');
button.setAttribute('type','image');
button.setAttribute('src','img/close.png');
card.appendChild(title);
card.appendChild(cardImage);
cardImage.appendChild(image);
cardImage.appendChild(button);
document.getElementById("lefty").appendChild(card);
};
To add a new card, you should set everything up from the ground. You should create the following in Javascript before adding it to the page:
<div class="card">
<h1>the_name</h1>
<div class="card-image">
<img src="the_link"/>
<input class="buttons" type="image" src = "img/close.png"/>
</div>
</div>
You already know how to get *'the_name'* and *'the_link'* (the variables for your cards). I'm gonna use those variables in my solution. First you have to create all the elements.
var card = document.createElement('div');
card.setAttribute('class','card');
var title = document.createElement('h1');
container.innerHTML = the_name;
var cardImage = document.createElement('div');
cardImage.setAttribute('class','card-image');
var image = document.createElement('img');
image.setAttribute('src',the_link);
var button = document.createElement('input');
button.setAttribute('class','buttons');
button.setAttribute('type','image');
button.setAttribute('src','img/close.png');
Now you want to paste all the elements to the webpage. First append the elements to each other, then append them to the place you want to get them to (in your case the body).
card.appendChild(title);
card.appendChild(cardImage);
cardImage.appendChild(image);
cardImage.appendChild(button);
document.body.appendChild(card);
You can delete an element in an odd way using javascript. First you have to get the domNode of the element you want to get rid of. For example one of the two nodes:
var unwanted = document.getElementsByTagName('a')[0];
var unwanted = document.getElementById('id_of_unwanted_item');
then you have to execute the following function:
unwanted.parentNode.removeChild(unwanted)
You have the basic idea, you just need to take it a few steps farther. For the delete you'll want to add an ID to each card and then call a JS function with that ID:
<div class="card" id="william">
<h1>William Finley (Phantom of the Paradise)</h1>
<div class="card-image">
<img src="img/avatars/william.png"/>
<input class="buttons" type="image" src = "img/close.png" onclick="removeCard('william')"/>
</div>
</div>
<script type="text/javascript">
var removeCard = function(cardId) {
var cardElement = document.getElementById(cardId);
cardElement.parentNode.removeChild(cardElement);
}
</script>
When you create a card (which Nicky explained well) make sure you add the ID and onclick event to your element generation.
I have been wrangling with my code all day with no luck in solving the problem.
My website has a series of images acting as navigation:
<div id="thumbs">
<img src="images/edwardsthumb1.jpg" class="thumb" border="0"/>
<img src="images/sample1thumb.jpg" class="thumb" border="0"/>
</div>
when these are clicked, content is added to blank divs:
<div id="image"> <!-- main image container -->
</div>
<div id="gallerytext"> <!-- text box -->
</div>
<div id="thumbset"> <!-- series of sub images/navigation -->
</div>
with this javascript:
$(function() {
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 -->
$(".image").click(function() { <!-- image variable is set when an image with class "image" is clicked -->
var image = $(this).attr("rel"); <!-- each image has appropriate rel attribute to fill variable -->
if (image == 'images/edwards1.jpg'){ <!-- different text and gallery loaded on click of specific image -->
var text = $('#gallerytext1').html();
$('#gallerytext').html(text);
var thumbset = $('#thumbset1').html();
$('#thumbset').html(thumbset);
$('#thumbset').hide();
$('#thumbset').fadeIn('slow');
}
if (image == 'images/sample1.jpg'){ <!-- different text and sub-gallery loaded on click of specific image -->
var text = $('#gallerytext2').html();
$('#gallerytext').html(text);
var thumbset = $('#thumbset2').html();
$('#thumbset').html(thumbset);
$('#thumbset').hide();
$('#thumbset').fadeIn('slow');
}
$('#image').hide(); <!-- main image changed -->
$('#image').fadeIn('slow');
$('#image').html('<img src="' + image + '"/>');
return false;
});
});
It works fine after the intial load, however if one of the "if" statements is triggered and the content is changed, images with the class .image within the div "thumbset" are now unclickable and the main image no longer changes. Images within the main navigation div: "thumbs" still work fine, and the "if" statements still go off.
all images are tagged and formatted as per the top code box in my post, and I cannot figure out why only images within "thumbset" decide to stop working.
I am very very green to Javascript, so any assistance will be greatly appreciated!
UPDATE: here is my updated code. Much cleaner now but the function is not working at all. I'm thinking the problem may be with the variable setting of "image" variable?
$(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=$(this).attr("rel");
var imid=$(this).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;
});
});
use
$(document).ready(function() {
var $doc = $(document.body);
$doc.on("click",".image", function() {//...
then bind all events from the $doc (chain them if different selectors
$doc.on(event,selector,function).on(ev,sel,fn)...
or if multiple events on same selector
$doc.on({
ev : function(e) {},
ev2 : function(e) {}
//...
},selector).on()...
to comment out in javascript use, it'll comment what's after in same line
//
instead of <!-- which is more meant to comment out html
your code in spaghetti like with many repeated instructions,
take out the common instructions in the if
define a pattern so to avoid using if(stg=='sthg')
for example you could do
<a ... data-idtoload="*id*">...
then
var imid=$(this).data("idtoload");
var text = $('#gallerytext'+imid).html();
$('#gallerytext').html(text);
var thumbset = $('#thumbset'+imid).html();
//...
no more if & your code is cut by 66%