0

I have a sticky menu/floater bar when a user scrolls down on the page ... using jQuery I add the floater-bar class to the #menu-wrapper.

My goal is to add an image within an anchor at the same time floater-bar class is added so that the logo is on the floater bar as well.

if ($(window).scrollTop() > $header_top_pos) {
  $("#menu-wrapper").addClass("floater-bar");
} else {
  $("#menu-wrapper").removeClass("floater-bar");
}

I have tried the following:

$("#menu-wrapper").append("<a href="#"><img src="image" /></a>");

Tried .add and .prepend as well

It makes the whole script fail as the floater-bar class no longer gets added into the menu.

1
  • 2
    Quotes are interrupting your append statement. Use single quotes within a double quoted string or escape the double quotes with \". Commented Mar 13, 2014 at 14:42

2 Answers 2

5

Do this instead:

$("#menu-wrapper").append("<a href='#'><img src='image' /></a>");

You're using " to start and end the append, but then using it also to assign a href and the src, which is canceling out the string.

So only use " to start and end it, and if you need quotes inside, use ', or escape the double quotes by using \".

If you wanted to do string concatenation (although not what you asked for, could come in handy later on), you do something like this:

$("#menu-wrapper").append("<a href='"+url+"'><img src='"+image+"' /></a>");

image and url would be variables. + is used to concatenate the string, giving you access to use variables within the string.

Sign up to request clarification or add additional context in comments.

3 Comments

alternatively, you could escape the double quotes \" if you are a huge fan of the double quote
Just said that as you commented! Thanks @Huangism
Thank you guys for such quick response. I ended up having to escape the double quotes, the script itself is being called by a php variable therefore would break when i used single quote.
2

try this

var anchor = $("a").attr("href","#");
var img = $("img").attr("src","img_source");
anchor.append(img);
$("#menu-wrapper").append(anchor);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.