I want to change a class when I click.
The class is icon icon_plus, and when i click i want that class to be icon icon_minus-06and if click again back tothe original
My HTML code
<i id="icon" class="icon icon_plus"></i>
My javascript code :
<script>
$("a.top-bar-trigger").click(ontop);
function ontop() {
$("#icon").toggleClass("icon icon_minus-06");
}
</script>
I am very weak with javascript
Thanks for the help.
Try to write toggleClass like this,
$("#icon").toggleClass("icon_plus icon_minus-06");
Since you are keeping icon class as a static one.
DEMO
Also as a side note, try to wrap your code inside document's ready handler. Since the selector would fail, if you keep your script inside header tag. But If you have placed your script in the end of body tag, then no issues. Anyway its better to use document's ready handler as it would make the code more procedural.
The code should be like this,
(function(){
function ontop() {
$("#icon").toggleClass("icon_plus icon_minus-06");
}
$(function(){
$("a.top-bar-trigger").click(ontop);
});
})();
You can solve this problem in two ways.
1) Using AddClass & RemoveClass Methods
$("a.top-bar-trigger").click(changeClass);
function changeClass() {
if($("#icon").hasClass('icon_plus')){
$("#icon").removeClass("icon_plus").addClass("icon_minus-06");
}
else{
$("#icon").removeClass("icon_minus-06").addClass("icon_plus");
}
}
2) Using ToggleClass
$("a.top-bar-trigger").click(changeClass);
function changeClass() {
$("#icon").toggleClass("icon_plus icon_minus-06");
}
You can check the JSFiddle Links here
1) https://jsfiddle.net/4vzsn4kt/
2) https://jsfiddle.net/zzq820eu/
You can try this way:
$("a.top-bar-trigger").click(function(){
$(".icon").toggleClass("icon_minus-06");
});
Fiddle: https://jsfiddle.net/5au3ywmz/2/
PROBLEM SOLVED
The code you have works if its run after the DOM is ready, you can see it working here: jsfiddle.net/hosw2wc9 – Adam Konieska
Related
I have html like this
(note -: I included j library on the top of page )
<div class="WIWC_T1">
Level of Course
</div>
to make it not clickable i used jquery like this
$(".WIWC_T1 a").click(function(){
return false ;
});
i tried this too
$(".WIWC_T1 a").off("click");
but onClick="call_levelofcourse();popup('popUpDiv1')" is still working on my page . what is soltuion to do it in very simple way ??
Another aproach (which not uses jQuery) is to use css class:
.disable-anchor{
pointer-events: none;
cursor: default;
}
and then just add this class to your anchor like:
<a href="javascript:void(0);"
class="disable-anchor"
onClick="call_levelofcourse();popup('popUpDiv1')">
Level of Course
</a>
P.S. check the availability of pointer-events before using it because this is the CSS3 feature.
Try this
$(".WIWC_T1 a").click(false);
To prevent events, like a when clicking, prevent that event like this:
$(".WIWC_T1").on("click", function(e)) {
e.preventDefault();
//Do your code, such show a popup
}
Level of Course
function call_levelofcourse(){
if(!$("a").hasClass("unclickable")){
/* your codes here */
}
}
$(".WIWC_T1 a").on("click", function(){
$(this).attr("onClick", false);
});
Please remember to add Jquery prototype
Thanks Vivek
$(".WIWC_T1 a").removeAttr('onclick');
I have this following jquery on my view:
$(document).ready(function() {
$(function() {
$('#link1').click(function() {
$('#link2').show();
$('#link1').hide();
$('#frame').attr('src', 'http://google.com/');
});
});
});
$(document).ready(function() {
$(function() {
$('#link2').click(function() {
$('#link1').show();
$('#link2').hide();
$('#frame').attr('src', 'http://yahoo.com/');
});
});
});
On pageload, the link2 is set to hide. What the jQuery does is: when the link with id link1 is clicked, it will show the link with idlink2 and hide itself. And vice versa.
My problem is it seems that my jQuery code can still be simplified. Is there other ways I can do what I wanted with simpler version? Thanks for the help!
Working example : http://jsfiddle.net/cuJBm/
$(document).ready(function() {
$(function() {
var linkSet = $('#link1').add('#link2')
linkSet.click(function() {
linkSet.toggle();
});
});
});
The add method allows you to add a different selector to the set of matchers, thus binding both clicks simultaneously. By saving the constructed set to a variable (linkSet), it stops you from having to traverse the DOM twice.
The only two assumption made here, are
1) That in the initial state only one is visible.
2) That the id structure is meaningful, useful, and classes will not suffice.
http://jsfiddle.net/cuJBm/1/
To answer your second question about setting an attribute on #frame. There are numerous ways of doing this. Perhaps the simplest is to add the following to your .click handler (after the toggle).
if ($(this).attr('id')=='link1'){
$('#frame').attr('src', 'www.google.com');
} else if ($(this).attr('id')=='link2'){
$('#frame').attr('src', 'www.yahoo.com');
}
Personally, I would probably add a custom attribute to your link elements, something like:
<a id='link1' iframe-source='www.google.com'>
<a id='link2' iframe-source='www.yahoo.com'>
And then: (again, just after the toggle):
source = $(this).attr('iframe-source');
$('#frame').attr(src, source);
The reason for saving source if is that if you attempt to get $(this) within the .attr on $('frame'), it will (as always) return the currently matched element, ie $('#frame').
Alternately (and very similiarly to the above approach), you could use the innerHTML of the link. For example:
<a id='link1'>link1<span style="display:none">www.google.com</span></a>
<a id='link2'>link2<span style="display:none">www.yahoo.com</span></a>
And then: (again, just after the toggle):
source = $(this).find('span').text();
$('#frame').attr(src, source);
Personally, I dislike this last method as it pollutes the DOM structure, leading to slightly more expensive rendering times, and (in my opinion) less readable code. Practically, all three methods work just fine.
<p class="link" style="display:none;" data-link="http://google.com/">sfdf</p>
<p class="link" data-link="http://yahoo.com/">ee</p>
$('.link').click(function() {
$('.link').toggle();
$('#frame').text($(this).data("link"));
});
jsfiddle :http://jsfiddle.net/xqDus/1/
Use jQuery toggle()
just add this
Google
Yahoo
target is id of the frame
$(function() {
$('#link1, #link2').click(function() {
$('#link1, #link2').toggle();
});
});
I've got my fiddle here, but I can't understand why it's not calling my function on the 'onmouseout' event.
http://jsfiddle.net/foreyez/Xf6LW/
any ideas?
Works fine, you just needed to put the function in the head (or body after the element is in the DOM) of the document.
jsFiddle example
It's because the functions you create in the JavaScript panel are not global when you have the onLoad option selected. Your JavaScript gets wrapped in a function.
If you do want them to be global you have to either do what j08961 suggested, by changing that dropdown to say no wrap (body or head) will work
The best solution would be to not set your event handlers from HTML, that's bad practice anyway, then you're not relying on global functions or mixing HTML and JS.
<div id="myDiv">
</div>
document.getElementById('myDiv').onmousemove = function() {
alert('here');
}
Side note: you should have noticed the error in the console saying that myFunc is undefined or something like it.
I think it's cause for jsfiddle, it declares all the javascript AFTER the HTML. The HTML is going to run and look for a myFunc and not find it. Then it's going to load the JS and it won't even run it.
Here you can see the changes : jsfiddle.
make myFunc as a global function;
I searched my code using firebug and got following generated code.
window.addEvent('load', function() {
//window.myFunc makes myFunc as a global function
// It can be accessed from any were inside current window.
window.myFunc = function myFunc(x)
{
alert('yo');
}
// function below is not available gloably.
function myFunct1(){
alert('yo1');
}
});
see jsfiddle
I want to change all the links in a div such that they no longer refer to a page, but run a JavaScript function when being clicked. To do so, I wrote this function:
function buildPageInDiv(htmlString){
console.log(typeof htmlString);
$div = $(htmlString).children("div#myDiv");
$div.children("a").each(function(i, element){toJavascriptLinks(element)});
document.getElementById("targetDiv").innerHTML = $div[0].innerHTML;
}
calling this function:
function toJavascriptLinks(element){
element.href="#";
element.onclick = function(){console.log('Yeah!')};
console.log(element);
}
Now, when I run buildPageInDiv, 'string' is printed on the console, all the "href" are changed to "#" and for every <a> within the div the console prints the element:
<a href="#">
No sign of the onclick here, and clicking on the link does not show anything on the console.
What am I missing here?
Edit:
I was seeking in the wrong place. The problem was that I was running toJavascriptLinks(element) before attaching the innerHTML to targetDiv. That was no problem for the href attribute, but it was for the onclick attribute. Solution is simply to put it in targetDiv first and than run toJavascriptLinks(element) on targetDiv :
function buildPageInDiv(htmlString){
console.log(typeof htmlString);
var content = $(htmlString).children("div#myDiv")[0].innerHTML;
document.getElementById("targetDiv").innerHTML = content;
$("div#targetDiv").children("a").each(function(i, element) toJavascriptLinks(element)});
}
Although the problem was not in the code I originally posted, the comprehensive answers below led me to the solution.
First: All type of selectors in jQuery, start with the dollar sign and parentheses: $()
Secondly: you need to close your statements with ;
Lastly: it is good practice to define your functions BEFORE you call them, instead of relying on javascript to hoist them to the top for you. This will also make jslint validate, whereas the other way round wouldn't!
So your code without your errors would look like:
function toJavascriptLinks(element){
element.href="#";
element.onclick = function(){alert('Yeah!');};
console.log(element);
}
$('div').children("a").each(function(i, element){toJavascriptLinks(element);});
See this fiddle for a working demo.
Good Luck!!
ABOUT YOUR UPDATED QUESTION:
That's quite an update to your question.
You don't see your onclick in console.log because you set the onclick event in the dom. If you wanted to see the onclick in console.log, you would add the function STRING using:
element.setAttribute('onclick', 'your function string');
Suppose in your html you have:
<a id="link_a" href="http://www.google.com">link 1</a>
<a id="link_b" href="http://www.duckduckgo.com">link 2</a>
And you have this javascript:
var lnkA=document.getElementById("link_a");
var lnkB=document.getElementById("link_b");
lnkA.onclick=function(){alert(this.innerHTML);};
lnkB.setAttribute('onclick','alert(this.innerHTML);');
console.log(lnkA.outerHTML);
console.log(lnkB.outerHTML);
Then console.log will contain:
<a id="link_a" href="http://www.google.com">link 1</a>
<a onclick="alert(this.innerHTML);" id="link_b" href="http://www.duckduckgo.com">link 2</a>
See this fiddle for a live example of this explanation.
I also think you are already using some form of jQuery (without you knowing it) because of your use of .children("div#myDiv"). To my knowledge this no plain vanilla javascript. And I think both plain vanilla javascript and jQuery would not select those divs with id 'myDiv' out of a plain html-string, so the code in your update would not do the job.
Finally, to adjust my answer to your updated question and expectation of the onclick-event being visible in the parsed html-source:
var htmlString='<div id="myDiv">link 1link 2</div><div id="otherDiv">link 3link 4</div>';
function toJavascriptLinks(element){
element.href="#";
element.setAttribute('onclick','console.log("Yeah!");');
console.log(element.outerHTML);
}
//no innerHTML on documentFragment allowed, yet on it's children it's allowed
var frag = document.createDocumentFragment().appendChild( document.createElement('div') );
frag.innerHTML=htmlString;
var $div = $(frag).children('div#myDiv');
$($div).children("a").each(function(i, element){toJavascriptLinks(element);});
var outp=document.getElementById("output");
outp.innerHTML=frag.innerHTML;
See this updated fiddle to see it in action.
That leaves the question: why on earth are you placing 'ninja' $-signs front of your variable names?
That's just the way the debugger displays an HTML element. It doesn't show all attributes - especially since you are setting the DOM property onclick to a function reference, which can't be displayed as the HTML attribute onclick which takes a string (which AFAIK can't be set with JavaScript see Luc's comment).
Try console.log(element.onclick); instead, it should display something like function() {...}.
Or doesn't the event handle work?
BTW, any reason you don't use jQuery to set the href and the handler?
$div.children("a").attr('href', '#').click(function(){console.log('Yeah!')});
One more thing: In most consoles you can click on <a href="#"> and it will display the DOM properties, which should include the event handler.
I would really use jQuery for this, it's quite simple.
$(function() {
$("div > a ").attr("href", "#").click(function(e) {
e.preventDefault();
doSomething();
});
});
var doSomething = function() {
alert("Woah, it works!");
}
See the following jsfiddle for it in action: http://jsfiddle.net/SsXtt/1/
Are you sure the element is correct? This works for me.
<a id="mylink">Test</a>
<script>
document.getElementById("mylink").onclick = function() {
alert("Works");
};
</script>
Function needs to be inside a string, try adding quotes?
As a javascript newbie, I am struggling to use a script with a variable that runs a bit of JQuery (and also struggling to use the right language here, I'm sure!)
The action I want to happen is to change the CSS class of a specific div, e.g. #det90, for which I have the following code (I have used the same on a $(window).load(function() and it works on a different set of divs):
$("#MYDIVIDHERE").switchClass("sdeth","sdet",50);
So I wrote the following:
<script type="text/javascript">
$(function revealCode(divID) {
$("#divID").switchClass("sdeth","sdet",50);
})
</script>
and called it from an anchor with:
onClick="revealCode('det90');"
I think the problem is that I don't know how to write the script and pass the variable in the brackets (divID) to the next line (where I've got "#divID"). Any help or pointers to tutorials gratefully received!
Solution
Thanks to all, but particularly to Caleb. I've scrapped the general function and the onClick, added an ID to the anchor and inserted the following for that anchor (and then repeated that for each anchor/div combination I want to use it on ... and it works :D
$("#linkID").click(function() {
$("#divID").switchClass("sdeth","sdet",50);
});
Change your code to: onClick="revealCode('#det90');"
$(function revealCode(selector) {
$(selector).switchClass("sdeth","sdet",50);
})
jQuery is powered by "selectors" -- similar to CSS syntax.
Don't quote your variable name. Just quote the "#" prefix.
<script type="text/javascript">
$(function revealCode(divID) {
$("#" + divID).switchClass("sdeth","sdet",50);
})
</script>
Change to:
<script type="text/javascript">
function revealCode(divID) {
$("#" + divID).switchClass("sdeth","sdet",50);
}
</script>
You don't need $() around the function
$("#divID") will look for an element with the ID divID, and not what was specified in your function parameter
This won't work. revealCode is local to that scope and not known outside. Also, you're not using the argument you've passed into your handler.
If you're using jQuery, use it to bind to the handler as well like this:
jQuery(document).ready(function() {
function revealCode(divID) {
$("#" + divID).switchClass("sdeth","sdet",50);
}
jQuery("#divID").click(function() {
revealCode('det90');
});
});
Move your onclick event handler attachment into javascript code. You should try not to mix your functional code with your html.
Anonymous version:
$('#myDiv').click(function () {
$(this).switchClass("sdeth","sdet",50);
});
Normal version:
var myFunction = function (element) {
$(element).switchClass("sdeth","sdet",50);
};
$('#myDiv').click(myFunction, {element: this});