Changing css styles with jQuery (within a container) - javascript

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.

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...

http://jsfiddle.net/JFwDw/34/
This is working for me.
Edit: I think that this is what you're trying to achieve!

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.
big text
$('#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');

Related

Use a link ONLY when javascript is disabled

I have a social networking site for my college community and its working fine. There is a feature to like a post by other users. Liking is triggered using javascript's onClick() function.
Recently due to security reasons, many of our members disabled javascript.
Is there any way to redirect a user to a particular page if javascript is disabled? Otherwise the script should work.
For a more discriptive detail, assume my current code is like:
Item
what i want is something like:
Like
**but href should be active only if onclick() function dont work. is that possible? **
my site is built with php codeigniter. any solutions?
Just return false on the function that is called in the onClick event.
So either make sure that likeFunction() returns false. Or, return false afterwards with onClick="likeFunction(); return false;".
In general, you should always put a link in the href and not rely exclusively on JS. An anchor tag should not be abused with the onclick event to create pseudo-buttons. You might consider using a button tag if no link has to be put in the href.
Also, the href should start with the protocol (http://www.example.com instead of www.example.com).
Side note: You might consider attaching the JS event by calling addEventListener instead of using the onClick attribute. There are different cons and pros using either methods. I suggest you to have a look at this answer: addEventListener vs onclick.
Edit: As WillardSolutions suggested, you can use preventDefault to ensure the link is not opened when the onClick event is called. For further details, I suggest you to have a look at this answer: event.preventDefault() vs. return false
Don't muddy up your HTML, simply enhance it with JavaScript (see: Progressive Enhancement). This can be easily achieved with a CSS class and a document selector.
Given the HTML:
Like
You can add a self executing JavaScript function just before the </body> tag:
<script>
(function() {
document.querySelectorAll('a.like').forEach(function(item) {
item.removeAttribute('href');
item.onclick = function() {
/* add the likeFunction functionality here */
};
});
})();
</script>
That's pretty basic; it loops through all <a> tags that have class="like", removes the href attribute and adds the functionality from your current likeFunction() to the click event (if you copy the code from the likeFunction() to where indicated).
Obviously if JavaScript is disabled, the DOM isn't updated and your original HTML remains in place.
Note: forEach() support may be sketchy in Microsoft browsers.
Why not just use preventDefault()
// if js is disabled, this doesn't execute at all,
// so the link will work by default and take the user to the url defined inside the `href` tag.
document.getElementById('myLink').addEventListener('click', function(e) {
e.preventDefault(); // This will tell the browser not to follow the link.
... Do Awesome stuff here all day long
});
DEMO

Prevent anchor tag to jump

It is my first post on SO, I am using it already quite a while, always found a solution via search. Now I'm starting to dig deeper into programming - right now learning Java Script - and I couldn't find the exact answer for my beginner problem:
I've created a simple photo gallery where the thumbnails point to the image via href. The images are not displayed by default. By clicking on a thumbnail, the corresponding image appears thanks to the :target pseudo element. This way I can bypass the cascading nature of my HTML structure and address elements higher in hierarchy.
See fiddle:
https://jsfiddle.net/ahu1kaqf/
The problem is, that this "hack" has the side effect of putting the image to the very top of the window due to its default anchor jump behavior.
So what I want to accomplish is to turn off or bypass just the jump behavior.
Therefore, solutions with JS like "preventDefault" or "return false" are not suitable as they turn off the complete anchor behavior.
My idea was to read the yScroll position just before the click and pass it to another function which triggers just after the page jump. By appending an onclick event on the anchor tag I found out that the function executes before the actual jump and I can read the current scrollY position:
function posY(){
console.log(window.scrollY);
scry = window.scrollY;
}
Then, after the anchor event has finished, I would like to pass the variable scry to another function which triggers just after the anchor jump to undo the jump:
function undoJump(){
window.scrollTo(0, scry);
}
It doesn't really work with a click event as the function triggers before the actual jump.
The js code in the fiddle is in script tags because putting just the functions into the js window (of course without script tags) shows an error in the console, I don't know why...
Sorry, I'm really a beginner, thank you all for your help!
https://jsfiddle.net/ahu1kaqf/1/
var classname = document.getElementsByClassName("thumb");
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener("click", posY);
}
function posY(e){
e.preventDefault();
console.log(window.scrollY);
}
Remove the onclick as it's just not the best way to do it. Add a class to the links OR use querySelectorAll based on the parent class. The benefit here is, you don't have to remember to add a class or a onclick. It's less code to deal with and easier to manage.
https://jsfiddle.net/ahu1kaqf/2/
In either case, you can stop the normal event behavior with e.preventDefault();
For the second part, you'll probably just want to set a global in this case. Set a global outside all of the functions and change it on click. You could probably get more complex with objects, and promises and such, but, honestly, it'd be just as easy to set a global value. It's good to try to avoid them, but they can be simple useful solutions depending on the overall complexity of the application in question.
Yes, you need to prevent the default action (which is a navigation action).
In modern browsers, that means you can do this (note I'm passing the global event object as a parameter):
<div class="thumb">thumb1</div>
Then in your js code you can do this:
function posY(e){
e.preventDefault()
console.log(window.scrollY);
}

removing dynamic javascript tag does not remove attached events

i'm creating an application where a user can make a html layout and attach javascript to it.
Now i'm trying to make it so when they click a button, they go to a preview mode where they can see it in action.. so when they click i add the javascript tag ( with their javascript) in the head of the iframe.. this all works fine!
But the problem is when they leave the preview mode, i remove the javascript tag, however when i have code like this:
$('#button').click(function()
{
alert("ok");
});
it still alerts ok when i click the html button (when not in previewmode!), which shouldn't happen!
It seems that when removing the javascript tag, the listeners aren't removed.. Or am i doing it wrong?
Now my question: is there a way to make it so these added eventlisterens are removed when i remove the script tag?
AND YES: i know you can remove eventhandlers with .off(), but since i already have event handlers attached, these will be removed also, and i don't want this!
So two options i can think off:
- rebuild the whole iframe
- store the eventhandlers that were added by the user and when leaving the preview mode, removing them.
Thanks in advance
Each time you "evaluate" JavaScript, it becomes part of the browser's "image", and whether the source is present on the page no longer matters. You need to manually unbind the event, or replace the html segment to which the event was bound.
To remove events from an html element, you can use:
element.parentNode.innerHTML = element.parentNode.innerHTML
This rebuilds the DOM tree using the same HTML.
you need to unbind event.
You can do it by using jquery unbind() or off()
like this:
$("#button").unbind("click");
or
$("#button").off("click");
Demo: http://jsfiddle.net/a6NJk/664/
jquery Doc: http://api.jquery.com/off/
Another good answer: Best way to remove an event handler in jQuery?
Set the event:
var $button = $('#button');
$button.on("click", function() {
alert("ok");
});
Take off the event:
$button.off("click");
You can take off that specific function too
var $button = $('#button');
var eventFunction = function() {
alert("ok");
});
// Set event up
$button.on("click", eventFunction);
// Take event off
$button.off("click", eventFunction);
If you want to remove all events from an element you can use
$("#yourSelector").off()
Because it's not jQuery in general but also vanilla javascript, it would be too much work to keep track of javascript changes, so rebuilding the iframe would be the best option here.

Links added via ajax do not have the same behavior as links present in the initial DOM

I am using this to generate an AJAX call when user clicks on link.
$('a').not('.noajax').click(function(event) {
event.preventDefault();
AJAXLoad($(this).attr('href'));
});
AJAXLoad is used to generate new content to some DIV. The thing is that when I generate new content which has links, the newly generated links do not behave the way I expect from the above code.
I know this might be caused by the fact that the newly added content doesnt have the old property (encountered similar problem with shadowbox addon image links), but I am not skilled enough in JS to modify my code so that it works. Any help?
You need to use event delegation.
$(document).delegate("a:not(.noajax)","click",function(e){
// do stuff
})
or for 1.7.2+
$(document).on("click","a:not(.noajax)",function(e){
// do stuff
})
You should also replace document with whatever element you are using as a target for AJAXLoad.
$.click(function() {}) only applies to elements that exist on the page when that line of code is evaluated.
You want to use $.live('click', function() {})
$.live() will watch for any new elements that appear that it should apply to.
Edit: spelled out explicitly -
$('a').not('.noajax').live('click', function(event) {
event.preventDefault();
AJAXLoad($(this).attr('href'));
});

jQuery is not catching click on some content loaded

I'm using jQuery 1.7.2 with Zoomy and jmpress plugins. Also I'm using boilerplate+bootstrap downloaded from initializr.com
I'm trying to create a "game" like [Waldo/Wally] when you have to find some character in a photo. Each photo has a different character to find.
I'm using jmpress as a presentation plugin to go from one photo to another every time the character is found. jmpress loads the content trough ajax (and I need that behavior) because I want a pretty fast load of the web.
Problem: The .on("click") event is not being caught on one of the elements that exist inside the content loaded.
As an example, I'll explain my problem with one of this characters (just taking parts of code).
I have in my index.html some divs to load the characters, I'll take the nurse character:
<div id="nurse" class="step container" data-src="women/nurse.html" data-x="7500">
Loading...
</div>
The jmpress load the data-src (women/nurse.html) trough ajax when the user is near to that div (step). It loads great.
This is the code of nurse.html
<script type="text/javascript">
new Image().src = "img/nurse_big.jpg";
</script>
<div class="descripcion">
<p>Bla, bla, bla.</p>
</div>
<div class="imagen">
<img src="img/nurse.jpg" alt="Find the nurse" />
</div>
As you can see, I have two divs loaded inside the #nurse div (that has .step class).
I have this code on my js/script.js file when I try to catch the click event:
$(".step").on("click", function(event){
console.log(event.target);
});
I'm also trying with "body" tag to see what happens
$("body").on("click", function(event){
console.log(event.target);
});
If you check the console while the message is showing (div.descripcion) it catch the event and print. But, after the div.descripcion is removed and the image appears, it dosen't. Like if that div.imagen or even elements inside it dosen't exist. The click event is not catched. I tried to catch mousemove event and It does.
Why is not catching the click? any idea?
You can see a working version: [Removed]
And the not working version: [Removed]
UPDATE: I forgot, if I use .on("click") it dosen't work. But if I use .on("mousemove") for example, it works. That's the weird part. .on() is working, but not for the click event.
UPDATE 2: I have removed the links of the live examples because they where dev versions. I'll publish the link to the final work when is published. Thanks to all of you for taking the time. Specially to #Esailija that gives me the answer.
Once again, you need to use on for content loaded later on:
$("body").on("click", ".step", function(event){
console.log(event.target);
});
Replace body with the closest static element that holds the .step elements.
Static means exist in the DOM when the you execute the line:
$(...).on("click", ".step", function(event){
Example:
$('#ContainerId').on("click", ".step", function(event){
// Do what you want.
});
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers
on docs
The zoomy plugin you are using does this:
'click': function () {
return false;
}
Since the element you are clicking when you are on the image, is actually the zoomy elements, those get to handle the events first. They handle it by returning false, which means doinge.stopPropagation() as well as e.preventDefault(). So the event won't even come to .imagen.
There is also unterminated multi-line comment in your code, not sure what that does but it can't be good. Consider just deleting code instead of commenting it out.
Anyway, clearing everything like this:
$.cache = {}; //Can also do $("*").off() I think
And then doing:
$(".step").on("click", ".imagen", function(event){
console.log(event.target);
event.preventDefault();
});
And it works fine. You might wanna edit the plugin to do this instead:
'click': function (e) {
e.preventDefault();
}
Alternatively you could look for a plugin that is developed by someone who knows what the hell they are doing or write it yourself.
In the documentation in http://zoomy.me/Options.html you can allow the plugin to have a clickable area by adding in true to the clickable option.
So when calling zoomy() on a element all you have to do is add a little bit of code inside the zoomy function.
$('.element').zoomy({clickable:true});
and that should fix everything,
The alternative way to catch the function on click event is just like below.
<div onclick="fireClickEvent();" > Just firing the click event!</div>
function fireClickEvent() {
console.log(event.target);
}

Categories