ncf
ncf

Reputation: 556

Changing css styles with jQuery (within a container)

Here is the jsFiddle: http://jsfiddle.net/JFwDw/2/

What I'm wanting to do is use links to change the font-size and line-height of paragraphs only within a division id'd "content". I've made another division to make sure it isn't changing anywhere else... can't get it to work after a while of playing around with it.

Thanks in advance.

Upvotes: 0

Views: 243

Answers (3)

dqhendricks
dqhendricks

Reputation: 19251

Well, for one, your links are being activated and reloading the page.

Typically when you write jQuery, you would attached the events using selectors, not using inline code. This let's you keep your JavaScript and HTML in separate files as well as allows jQuery to remove events when needed.

<a href="#" id="bigText">big text</a>

$('#bigText').click( function(event) {
   // code here
} );

Then to prevent the default action (following the link), you can use the jQuery method, prevent default action.

$('#bigText').click( function(event) {
   event.preventDefaultAction();
   // code here
} );

You may also what to wrap you event binding code withing a document ready event in order to make sure that the DOM is loaded before trying to attach events to it.

$(document).ready( function() {
   $('#bigText').click( function(event) {
      event.preventDefaultAction();
      // code here
   } );
} );

Also, you would typically want to add a class to change an element's styles rather than using jQuery to change the style. It's more performant. Also, if you want to only affect element within a container, you can use the jQuery "find" method to do so.

$('#someContainer').find('p').addClass('someClass');

Upvotes: 1

silentw
silentw

Reputation: 4885

http://jsfiddle.net/JFwDw/34/

This is working for me.

Edit: I think that this is what you're trying to achieve!

Upvotes: 1

sachleen
sachleen

Reputation: 31141

You want to change which selector you're using. Instead of doing to all p tags, you just want the ones under #content

$("#content p, #content ul").css()

DEMO

Your links also link to <a href=""... which causes the page to reload. I changed it to href="#" so this doesn't happen. You could also prevent the default event from happening inside the functions.

function origText() {
    event.preventDefault()
    ...

On a side note, I can't figure out why the functions are not working in the JS part of the fiddle...

Upvotes: 3

Related Questions