The code works well, but I have no control of my layout. It toggles between two button states correctly once the link is pressed. How do I call the 'plus class' before the link is pressed? Please help. Also, I've tried divs and spans to organize it, but it needs some tweeking
Thanks,
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
</head>
<style type="text/css">
#h6{font-size: 12px; padding-right: 0px;}
.plus{left:0px;height:33px;width:32px; background:url('sprite.gif') 0 0px;}
.minus{left:0px;height:33px;width:32px; background:url('sprite.gif') 0 -34px;}
</style>
<h6 id="deToggle">Larger</h6>
<script language="javascript">
var click = 0%2;
var fontSizes = [14, 16]
$('#deToggle').toggle(
function(){
var sprot = $('#deToggle');//
var tog = $('#deToggle');
tog.html('Larger');
$('#OurText').css('fontSize', fontSizes[1] + 'px');
$(this).val("-");
tog.addClass('plus');
tog.removeClass('minus');
},
function(){
var tog = $('#deToggle');
tog.html('Smaller');
$('#OurText').css('fontSize', fontSizes[0]+ 'px');
$(this).val("+");
tog.removeClass('plus');
tog.addClass('minus');
});
</script>
<p id="OurText">My Text!!!</p>
</html>
sprit.gif rollover image
I reply 2 days before something like this
see here
ask for help
DEMO
Do you mean you want to apply the class on the initial page load?
Call the code to add the plus class on the initial page load. I've also refactored your code into functions and put it all in jQuery's document.ready function
$(document).ready(function(){
Plus();
$('#deToggle').toggle(function(){
Plus();
}, function(){
Minus();
});
});
function Plus(){
var sprot = $('#deToggle');//
var tog = $('#deToggle');
tog.html('Larger');
$('#OurText').css('fontSize', fontSizes[1] + 'px');
$(this).val("-");
tog.addClass('plus');
tog.removeClass('minus');
}
function Minus(){
var tog = $('#deToggle');
tog.html('Smaller');
$('#OurText').css('fontSize', fontSizes[0]+ 'px');
$(this).val("+");
tog.removeClass('plus');
tog.addClass('minus');
}
You need to add doctype for css to work. Add this before the head tag
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
This is because you didn't set the initial size. you can use either css or javascript for that.
Recommended way is to use CSS. Add this to your style
#OurText {
font-size: 14px;
}
See Demo. http://jsfiddle.net/RV5LE/
I have cleaned your code a bit. and next time post your question with a copy on jsfiddle
css('fontSize', fontSizes[0]+ 'px');
Should be:
css('font-size', fontSizes[0]+ 'px');
↑
That fontSize is used in animate().
Also you do not need that + 'px' all numeric css values can be given as numeric.
Related
Is there any way possible to load a Google Translate widget in the sidebar and one in the footer, for example.
Every way I've tried has only loaded so that both appear in the location of the first instance on the page.
After a bit of tinkering I kinda felt obligated to solve the puzzle! You can skip to the good part by checking out the jsfiddle: (it works as of now but knowing google it might not tomorrow)
http://jsfiddle.net/melfy/15zr6ov0/
Lets begin:
First google translate is loaded and adds a listener for a select box it adds to the DOM after you call the right element but we need that change event to call a change for a select box we're going to clone from the original one to get google to update the translation, this gets a bit messy as we over take the prototype (which is usually bad practice)
Start by adding your header element:
<div id="google_translate_element"></div>
Then we add our footer element:
<div id="google_translate_element2"></div>
Next we pull in the google translator
<script type="text/javascript" src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
Now we get to the good part:
<script type="text/javascript">
// store google translate's change event
trackChange = null;
pageDelayed = 3000;
// overwrite prototype to snoop, reset after we find it (keep this right before translate init)
Element.prototype._addEventListener = Element.prototype.addEventListener;
Element.prototype.addEventListener = function(a,b,c) {
reset = false;
// filter out first change event
if (a == 'change'){
trackChange = b;
reset = true;
}
if(c==undefined)
c=false;
this._addEventListener(a,b,c);
if(!this.eventListenerList)
this.eventListenerList = {};
if(!this.eventListenerList[a])
this.eventListenerList[a] = [];
this.eventListenerList[a].push({listener:b,useCapture:c});
if (reset){
Element.prototype.addEventListener = Element.prototype._addEventListener;
}
};
function googleTranslateElementInit() {
new google.translate.TranslateElement({ pageLanguage: 'en' }, 'google_translate_element');
let first = $('#google_translate_element');
let second = $('#google_translate_element2');
let nowChanging = false;
// we need to let it load, since it'll be in footer a small delay shouldn't be a problem
setTimeout(function(){
select = first.find('select');
// lets clone the translate select
second.html(first.clone());
second.find('select').val(select.val());
// add our own event change
first.find('select').on('change', function(event){
if (nowChanging == false){
second.find('select').val($(this).val());
}
return true;
});
second.find('select').on('change', function(event){
if (nowChanging){
return;
}
nowChanging = true;
first.find('select').val($(this).val());
trackChange();
// give this some timeout incase changing events try to hit each other
setTimeout(function(){
nowChanging = false;
}, 1000);
});
}, pageDelayed);
}
</script>
You can change the pageDelayed variable to trigger quicker or slower but if it's in your footer, bumping it up to delay longer may help it work more efficiently depending on your page load
Unfortunately, you can not have the widget be loaded more than once in a single page. Google just doesn't allow for that. One potential workaround would be putting the code in an iFrame and then putting two iFrames onto your webpage.
Create a file called iframe.html
<html>
<head>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit">
</head>
<body>
<div id="google_translate_element"></div>
<script type="text/javascript">
function googleTranslateElementInit(){
new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}
</script>
</body>
</head>
</html>
In your other file put code something like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Google Translate</title>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?b=googleTranslateElementInit"></script>
</head>
<body>
<div id="header" style="background-color: red;">
<iframe src="iframe.html"></iframe>
<strong>A</strong>
</div>
<div id="footer" style="background-color: blue;">
<iframe src="iframe.html"></iframe>
<strong>B</strong>
</div>
</body>
</html>
I want to create a function for showing pop or status when user typing something in field, I want to do it without submitting form, I have try following function but its not working properly can anyone let me know where the problem..........?
Javascript
<script type="text/javascript">
document.getElementById('confirm').addEventListener('change', checkFile, false);
approveletter.addEventListener('change', checkFile, false);
function checkFile(e) {
if ($('#confirm').val().length > 0) {
alert("txt");
}
}
</script>
HTML
<input type="text" name="text" id="confirm">
Just listen to the onkeyup and onkeydown events. I included a jsfiddle that might help.
jsfiddle
Edit - The Latest Update
Okay, I see you've got your fiddle from Vivek, but you might be interested in this as well. Now I get completely what you want to achieve, and here's a short description. The best practice is to split JavaScript from HTML and avoid putting JavaScript inside HTML head and body as much as you can.
So, first create three files: Test.js Example.html and Test.css. Of course, you also need jQuery file which you just include here inside the head. In Example.html put the following code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="Test.css"/>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript" src="Test.js"></script>
</head>
<body>
<input type="text" id="test"/><span id="popup"></span>
</body>
</html>
In Test.css add some style to your pop-up span element (you could also use division element and style it to your liking if you want fixed height and width, add shadows and so on):
#popup {
background-color: red;
color: white;
display: none;
}
And finally, put the following JavaScript code in Test.js:
$(document).ready( function() {
$("#test").keyup( function() {
if($("#test").val().length>5) {
$("#popup").fadeIn();
$("#popup").html("Invalid length. Maximum is 5.");
}
else {
$("#popup").fadeOut();
}
});
});
By dividing JavaScript, CSS and HTML into separate files, you get much tidier HTML and separated styling and client-side logic from markup.
Old Answer
Wrap the code inside $(document).ready().
Like this:
$(document).ready(function() {
document.getElementById('confirm').addEventListener('change', checkFile, false);
approveletter.addEventListener('change', checkFile, false);
});
function checkFile(e) {
if ($('#confirm').val().length > 0) {
alert("txt");
}
}
Also, addEventListener is not available in IE8 and below. You could use the onchange event, like this:
$(document).ready(function() {
document.getElementById("confirm").onchange = checkFile;
});
There is a similar method for IE8 and earlier called attachEvent. In case of using the attachEvent method, it would look something like the following:
$(document).ready(function() {
document.getElementById('confirm').attachEvent('change', checkFile);
approveletter.attachEvent('change', checkFile);
});
You could also use the jQuery.change() as suggested in the comments by Protron:
$(document).ready(function() {
$("#confirm").change(function() {
if ($('#confirm').val().length > 0) {
alert("txt");
}
});
});
And of course it's possible to do it without the classic alert pop-up window. You could create your own HTML division element with display:none and show it when necessary. Just send me a note in the comments if you need instructions on that as well.
Using this, you need not click the web page.
<input type="text" name="text" id="confirm"><br /><br />
<span id="status" ></span>
<script type="text/javascript">
$('#confirm').keyup(function () {
if ($('#confirm').val().length > 0) {
$('#status').html("Text entered");
}
else
{
$('#status').html("Text removed");
}
}
)
</script>
I want create animation on mousemove in angularjs. I found example
https://docs.angularjs.org/api/ng/directive/ngMousemove
but i want to run function.
So inside of body
<body data-ng-mousemove="squareRotate()">
And js:
$scope.squareRotate = function(){
alert();
};
but i cant make it work. How can i manage it without puting it inside of controller ?
Since you didn't post your complete code, one can only guess. I am guessing that either the place of your body is really small, so you don't really move the move over the body, or angularjs application and controller are not properly initialised.
In order to give the html and body enough room, use the following:
html, body {
width: 100%;
height: 100%;
}
I created a working demo in fiddle. The only difference is that I don't use alerts, but a counter, which increases, when you move your mouse over the field.
testApp.directive('testDir', function () {
return function (scope, element) {
var el = element[0];
el.addEventListener(
'mousemove',
function () {
alert('test');
},
false
);
}
});
You may try it here: http://jsfiddle.net/AfNH9/4/
If you meant something different, please specify further.
Use directive:
I update the example to use a directive. The directive is bound to the body tag and uses an eventListener on "mousemove". If you move the mouse over the "Result" window in fiddle, you will see the alert window. http://jsfiddle.net/AfNH9/6/
Please see here : http://plnkr.co/edit/tpl:FrTqqTNoY8BEfHs9bB0f?p=preview
HTML:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js" data-semver="1.2.19"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl" data-ng-mousemove="squareRotate()">
<p>Hello {{name}}!</p>
</body>
</html>
js:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.squareRotate = function(){
alert();
};
});
So I'm fairly new to javascript, and I'm trying to use a simple if...else statement to toggle between showing and hiding a div element. My HTML page looks like this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
<style type="text/css">
#fluffy {
height:200px;
width:200px;
background-color:yellow;
display:block;
}
#pepper {
height:200px;
width:200px;
background-color:green;
display:block;
}
</style>
</head>
<body>
<div id="fluffy"></div>
<div id="pepper" onclick="changeState()"></div>
<script type="text/javascript">
function changeState() {
var divState = document.getElementById('fluffy').style.display;
if (document.getElementById('fluffy').style.display == 'block') {
document.getElementById('fluffy').style.display = 'none';
}
else if (document.getElementById('fluffy').style.display == 'none') {
document.getElementById('fluffy').style.display = 'block';
} else {
alert('test error message');
}
}
</script>
</body>
</html>
When I load the page in my browser, I receive an alert box containing 'test error message'. My original code had document.getElementById('fluffy').style.display stored in a variable called divState, but this didn't even give me an alert box, it didn't do anything. I get the feeling I'm using == wrong or something, but I'm really not sure. I've used ===, and when that didn't work I switched to ==, which is in the code above.
If anyone knows what exactly I'm doing wrong, I would appreciate the help.
Thanks, Harold
Alright, it looks like you guys fixed my problems. I can't thank you enough, and I will definitely look into jQuery!
Try changing the onclick to be this
<div id="pepper" onclick="changeState"></div>
document.getElementById('fluffy').style.display is ''. Since you're setting styles with a stylesheet, you'll have to use getComputedStyle (plus friends for cross-browser compatibility). You can find an example cross-browser implementation in the answer to Get all computed style of an element.
I know, you're trying to learn JavaScript what I also want to encourage, but with jQuery, this whole stuff would be a one-liner plus crossbrowser-friendly etc.
<div id="fluffy"></div>
<div id="pepper"></div>
The <script> contains just:
$("#pepper").click(function () { $("#fluffy").toggle(); });
Try it out at JSFiddle.
When the page first loads, the div doesn't have any inline styles. element.style reads inline styles only.
You will need to render the div with style="display:block;" or if you can't/don't want to do that, look into getComputedStyle options for your supported browsers
Use computed style:
<div id="fluffy"></div>
<div id="pepper" onclick="changeState()"></div>
<script type="text/javascript">
function changeState() {
var fluffy = document.getElementById('fluffy');
var divState = window.getComputedStyle(fluffy).display;
if (divState == 'block') {
fluffy.style.display = 'none';
}
else if (divState == 'none') {
fluffy.style.display = 'block';
} else {
alert('test error message');
}
}
</script>
jsFiddle
I tought $('#my_id1') was the same thing as document.getElementById('my_id1'). But it is parently not. What is the difference?
(function( $ ) {
$.fn.simple_hide_function = function() {
var $t = this;
$t.hide();
};
})( jQuery );
$(window).load(function () {
var $div1 = $('#my_id1');
var $div2 = document.getElementById('my_id2');
$div1.simple_hide_function(); // this is working
$div2.simple_hide_function(); // but this is not working
});
Adding example to make it more clear:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div id="my_id1" style="height:100px;background:#f00">div1</div>
<div id="my_id2" style="height:100px;background:#f00">div2</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
(function( $ ) {
$.fn.simple_hide_function = function() {
var $t = this;
$t.hide();
};
})( jQuery );
$(window).load(function () {
var $div1 = $('#my_id1');
var $div2 = document.getElementById('my_id2');
$div1.simple_hide_function();
$div2.simple_hide_function();
});
</script>
</body>
</html>
Difference is that first one returns a jquery object while the second returns a DOM element.
But these statements are equivalent:
document.getElementById('my_id2') <-> $('#my_id1').get(0)
or
document.getElementById('my_id2') <-> $('#my_id1')[0]
The first returns a jQuery object with that div as its only member. You can use jQuery functions on the object to manipulate it.
The second returns a DOMElement using the browser's built-in methods.
$('#my_id1') // Returns a jQuery object
And
getElementById('my_id1') // Returns a DOM object.
To get the DOM object of a jQuery object, you can call:
$('#my_id1').get()
jQuery can match more than one object with a selector, so to get the second matching DOM element:
$('#my_id1').get(1) // 1 = item #2 (zero-based index)
And to get matching DOM elements from the END of the collection, you can use a negative number, the distance from the end of the matched elements you want to retrieve, so -1 gets the last item.
$('#my_id1').get(-1) // gets the last item of the matched elements
Use my_id1:
var $div2 = document.getElementById('my_id1');
According to me, there is difference in its rendering in Browsers.
As if we do not use document. This will not work in IE browsers.
But only work in other browsers.