Mike Earley
Mike Earley

Reputation: 1293

javascript function using jquery addClass() method does not add class

The script works, creates everything correctly, etc., but the jquery addClass method isn't adding the class. I'm new to using jquery methods in a javascript function, any help is appreciated, including alternate methods for adding the appropriate classes without using jquery.

function thumbnail(Img, Element, Modal, ModalTitle) {
"use strict";
/*jslint browser:true*/
/*global $, jQuery*/
//this function will append an anchor tag with the appropriate functionality, accepting inputs on the image filename, attaching element, and modal
//Img = full filename in format of foo.png
//Element = the ID of the element within which the thumbnail anchor will be placed
//Modal = the ID of the modal
//ModalTitle = Text used for title of the modal and title of the caption
var image, element, modal, loc, output, iUrl, modal_loc, modal_output, mtitle;
image = Img;
element = Element;
modal = Modal;
mtitle = ModalTitle;
iUrl = "/design-library/images/thumbs/" + image;
output = "<a href='#' data-reveal-id='" + modal + "'>";
output += "<img class='sample_img' src='" + iUrl + "' alt='" + mtitle + "' />";
output += "</a>";
output += "<p class='caption'>" + mtitle + "</p>";
modal_output = "<h1>" + mtitle + "</h1>";
modal_output += "<img src='" + iUrl + "' alt='" + image + "' /><a class='close-reveal-modal'>&#215;</a>";
//create the modal container
$(modal).addClass('reveal-modal');
modal_loc = document.getElementById(modal);
modal_loc.innerHTML = modal_output;
//the end of the script gets the element and adds the anchor tag that exists in output
$(element).addClass('samples');
loc = document.getElementById(element);
loc.innerHTML = output;
}

Upvotes: 1

Views: 2788

Answers (3)

David Hellsing
David Hellsing

Reputation: 108500

if modal is an ID string, you need to do:

$('#'+modal).addClass('reveal-modal');

Upvotes: 2

Andrei
Andrei

Reputation: 56716

Since modal and element are IDs, you should correct your selectors to use them as ones:

$('#' + modal).addClass('reveal-modal');
$('#' + element).addClass('samples');

Side note. Once you have found the DOM element with jQuery, there is no need to perform the second search with getElementById:

var modal_loc = $('#' + modal);
modal_loc.addClass('reveal-modal');
modal_loc.html(modal_output);

Upvotes: 5

Pow-Ian
Pow-Ian

Reputation: 3635

Try changing:

$(element).addClass('samples');

to

$('#' + element).addClass('samples');

Upvotes: 1

Related Questions